1/18
Looks like no tags are added yet.
Name | Mastery | Learn | Test | Matching | Spaced | Call with Kai | Chat |
|---|
No analytics yet
Send a link to your students to track their progress
Write a fragment of code that will read words from the keyboard until the word done is entered. For each word except done, report whether its first character is equal to its last character. For the required loop, use a
a. while statement
b. do-while statement
Scanner keyScan = new Scanner(System.in);
boolean notDone = true;
while(notDone){
System.out.println("");
String word = keyScan.nextLine();
String checkFirst = word.substring(0, 1);
String checkLast = word.substring(word.length() - 1);
if(word.equalsIgnoreCase("done")){
notDone = false;
}else if(checkFirst.equalsIgnoreCase(checkLast)){
System.out.println(word + " does match");
}else{
System.out.println(word + " does not match");
}
Scanner keyScan = new Scanner(System.in);
boolean notDone = true;
do{
System.out.println("");
String word = keyScan.nextLine();
String checkFirst = word.substring(0, 1);
String checkLast = word.substring(word.length() -
1);
if(word.equalsIgnoreCase("done")){
notDone = false;
}else if(checkFirst.equalsIgnoreCase(checkLast)){
System.out.println(word + " does match");
}else{
System.out.println(word + " does not match");
}
}while(notDone);
Develop an algorithm for computing the month-by-month balance in your savings account. You can make one transaction—a deposit or a withdraw - each month. Interest is added to the account at the begging of each month. The monthly interest rate is the yearly percentage rate divided by 12.
1. Integer yearlyInterestRate / 12.
2. Interger savingsAmount.
3. boolean hasTransaction = true.
4. If a withdrawl or deposit has been made, change
hasTransaction to false.
5. Monthly interest = savingsAmount + ((savingsAmount * yearlyInterestRate ) / 100);
6. Show current month saviingsAmount.
Develop an algorithm for a single game of guessing at a secret five-digit code. When the user enters a guess at the code, the program returns two values: the number of digits in the guess that are in the correct position and the sum of those digits. For example, if the secret code is 53840, and the user guesses 83241, the digits 3 and 4 are in the correct position. Thus, the program should respond with 2 and 7. Allow the user to guess a fixed number of times.
1. Generate random 5-digit code.
- int randomCode;
2. Take user input of code.
- int userCode;
3.Keep track of what was correct, and the sum of
the correct integers.
- Create int correct and int correctSum.
4.Limit user to certain amount of guesses.
- Create userGuesses.
5. Compare randomCode with userCode.
6. Find the correct number.
- For each correct number increase correct by
one.
- Take each correct number, add their sum and
add that value to correctSum.
7. Display the result of correct and correctSum, the
set correct and correctSum to 0.
8. Repeat until either userGuesses has turned to 0,
or user has the correct code.
Write a fragment of code that will compute the sum of the first n positive odd integers. For example, if n is 5, you should compute 1 +3 + 5 +7 + 9.
Scanner keyScan = new Scanner(System.in);
int user = keyScan.nextInt();
int n = user * 2;
int userNum = user;
int sum = 0;
for(;0
Convert the following code so that it uses nested while statements instead of for statements:
int s = 0;
int t = 1;
for (int i = 0; i < 10; i++)
{
s = s + i;
for (int j = i; j > 0; j−−)
{
t = t * (j - i);
}
s = s * t;
System.out.println("T is " + t);
}
System.out.println("S is " + s);
int s = 0;
int t = 1;
int i = 0;
while ( i < 10)
{
s = s + i;
while (j > 0)
{
t = t * (j - i);
j−−
}
s = s * t;
System.out.println("T is " + t);
i++
}
System.out.println("S is " + s);
Write a for statement to compute the sum 1 + 2^2 + 3^2 + 4^2 + 5^2 + ... + n^2.
System.out.println("This program will take a user input,"
+ "\nand compute their power, then add their "
+ "\nsum together.");
Scanner keyScan = new Scanner(System.in);
int userNumber = keyScan.nextInt();
int sum = 0;
for(int start = 1; start
(Optional) Repeat the previous question, but use the comma operator and omit the for statement's body.
Scanner keyScan = new Scanner(System.in);
int userNumber = keyScan.nextInt();
int power = 0;
int total = 0;
for(int start = 1, sum = 0; start
Write a loop that will count the number of blank characters in a given string.
Scanner keyScan = new Scanner(System.in);
String userString = keyScan.nextLine();
int userLength = userString.length();
int space = 0;
for(int n = 0; n
Write a loop that will create a new string that is the reverse of a given string.
Scanner keyScan = new Scanner(System.in);
String userString = keyScan.nextLine();
int userLength = userString.length();
int userTotal = userLength;
String newStringChar;
for(int n = userLength; n >= 0; n--){
if(n == userTotal){
newStringChar = userString.substring(n);
}else{
newStringChar = userString.substring(n, n+ 1);
}
System.out.print(newStringChar);
}
Write a program that will compute statistics for eight coin tosses. The user will enter either an h for heads or a t for tails for the eight tosses. The program will then display the total number and percentages of heads and tails. use the increment operator to count each h and t that is entered. For example, a possible sample dialogue between the program and the user might be
For each coin toss enter either h for heads or t for tails.
First toss: h
Second toss: t
Third toss: t
Fourth toss: h
Fifth toss: t
Sixth toss: h
Seventh toss: t
Eighth toss: t
Number of heads: 3
Number of tails: 5
Percent heads: 37.5
Percent tails: 62.5
import java.util.Scanner;
public class CoinToss {
public static void main(String[] args){
double heads = 0, tails = 0, headsPerc, tailsPerc;
System.out.println("This program will read 8 user
inputs"
+ "\nof a coin toss, and display the "
+ "\npercentage of each collective toss.");
System.out.println("\n For each coin toss enter
either "
+ "h for heads or t for tails.");
Scanner keyScan = new Scanner(System.in);
System.out.println("");
for(int n = 1; n
Suppose we attend a party. To be sociable, we will shake hands with everyone else. Write a fragment of code using a for statement that will compute the total number of handshakes that occur. (Hint: Upon arrival, each person shakes hands with everyone that is already there. use the loop to find the total number of handshakes as each person arrives.)
Scanner keyScan = new Scanner(System.in);
int guests = keyScan.nextInt();
int handShakes = 0;
for(int n = 1; n
Define an enumeration for each of the months in the year. Use a for-each statement to display each month.
enum Months{
January, February, March, April, May, June, July,
August, September, October, November,
December
};
public static void main(String[] args){
for(Months nextMonth: Months.values()){
System.out.println(nextMonth);
}
}
Write a fragment of code that computes the final score of a baseball game. Use a loop to read the number of runs scored by both teams during each of the nine innings. Display the final score afterwards.
int runs = 1;
int team1 = 0;
int team2 = 0;
String team1Score = "s";
String team2Score = "s";
boolean game = true;
do{
if(runs != 10){
if(team1Score.equals("s")){
team1++;
}else if(team1Score.equals("s")){
team2++;
}else{
game = false;
}
}while(game);
System.out.println("Team One Score: " + team1);
System.out.println("Team One Score: " + team2);
Suppose that you work for a beverage company. The company wants to know the optimal cost for a cylindrical container that holds a specified volume. Write a fragment of code that uses an ask-before-iterating loop. During each iteration of the loop, your code will ask the user to enter the volume and the radius of the cylinder. Compute and display the height and cost of the container. Use the following formulas, where V is the volume, r is the radius, h is the height, and C is the cost.
*See page 249, question 14 for formula.
boolean run;
int start = JOptionPane.showConfirmDialog(null, "Start program", "Cyclinder Cost", JOptionPane.YES_NO_OPTION);
if(start == YES_OPTION){
run = true;
}else{
run = false;
System.exit(0);
}
while(run){
double h;
double c;
String volume =
JOptionPane.showInputDialog("Enter volume of
cylinder");
double v = Double.parseDouble(volume);
String radius =
JOptionPane.showInputDialog("Enter radius of
cylinder");
double r = Double.parseDouble(radius);
h = v / (PIE / (r * r));
c = 2 * PIE * r * (r + h);
JOptionPane.showMessageDialog(null, "Total
height of cylinder"
+ "\n" + h
+ "\nTotal cost of cylinder"
+ "\n" + c);
int rerun = JOptionPane.showConfirmDialog(null,
"Rerun Program?", "Cyclinder Cost",
JOptionPane.YES_NO_OPTION);
if(rerun == YES_OPTION){
run = true;
}else{
run = false;
System.exit(0);
}
}
System.exit(0);
Suppose that we want to compute the geometric means of a list of positive values. To compute the geometric mean of k values, multiply them all together and then compute the kth root of the value. For example, the geometric mean of 2, 5, and 7 is 3√2 x 5 x7. use a loop with a sentinel display value to allow a user to enter an arbitrary number of values. Compute and display the geometric mean of all the values, excluding the sentinel. (Hint: Math.pow(x, 1.0/k) will compute the kth root of x.)
double k = 0;
double kSum = 0;
double root = 0;
System.out.println("This program will compute the geometric"
+ "\nmeans of k values, where k will be"
+ "\nthe value you enter."
+ "\nWhen done, insert a negative number.");
while(k >= 0){
Scanner keyScan = new Scanner(System.in);
k = keyScan.nextDouble();
kSum *= k;
root++;
}
double sum = Math.pow(root, 1.0/k);
System.out.println(sum);
Imagine a program that compresses files by 80 percent and stores them on a storage media. Before the compressed file is stored, it must be divided into blocks of 512 bytes each. Develop an algorithm for this program that first reads the number of blocks available on the storage media. Then, in a loop, read the uncompressed size of a file and determine whether the compressed file will fit in the space left on the storage media. If so, the program should compress and save the file. It continues until it encounters a file that will exceed the available space on the media. For example, suppose the media can hold 1000 blocks. A file of size 1100 bytes will compress to size 880 and require 2 blocks. The available space is now 998 blocks. A file of size 20,000 bytes will compress to size 16,000 and require 32 blocks. The available space is now 966.
• Check if there is available space
• If space is available, do the following:
- Create a while loop, to use while there is space.
- If space is available then compress file by 80%.
- Divide file into 512 bytes, for every 512 byte take
one block.
- When done, loop to new file, and repeat while
loop.
• If no space is available, send error message that informs user of not enough space.
Create an applet that draws a pattern of circles whose centers are evenly spaced along a horizontal line. Use six constants to control the pattern:
The number of circles to draw, the diameter of the first circle, the x- and y- coordinates of the center of the first circle, the distance between adjacent centers, and the change in the diameter of each subsequent circle.
import javax.swing.JApplet;
import java.awt.Color;
import java.awt.Graphics;
public class CircleApplet extends JApplet {
public static final int DIAMETER = 10;
public static final int X_CO = 10;
public static final int Y_CO = 10;
public static final int CIRCLENUMBER = 6;
public static final int DIAMETERINC = 10;
public static final int X_MOVE = 70;
public void paint(Graphics g){
for(int x = 1; x
What does the following fragment of code display? What do you think the programmer intended the code to do, and how would you fix it?
int product = 1;
int max = 20;
for (int i = 0; i
• Keeps track of the maximum amount of products
they can have.
• To keep track of the product quantity..
• int product = 1;
int max = 20;
for (int i = 0; i
What does the following fragment of code display? What do you think the programmer intended the code to do, and how would you fix it?
int sum = 0;
int product = 1;
int max = 20;
for (int i = 1; i
• To have a sum of all the products they have is stock.
• Check quantity and space for the products.
• int sum = 0;
int product = 1;
int max = 20;
for (int i = 1; i