Start with a year value of 0, a column for the interest, and a balance of $10,000.
year | interest | balance |
---|---|---|
0 | $10,000 | |
Repeat the following steps while the balance is less than $20,000. Add 1 to the year value. Compute the interest as balance x 0.05 (i.e., 5 percent interest). Add the interest to the balance. Report the final year value as the answer.
Because the interest earned also earns interest, a bank balance grows exponentially.
while (condition) { statements }
while (balance < targetBalance) { year++; double interest = balance * RATE / 100; balance = balance + interest; }
Figure 1 Flowchart of a while Loop
while (balance < targetBalance) { year++; double interest = balance * RATE / 100; balance = balance + interest; } // interest no longer declared here
Figure 2 Execution of the Investment loop
The investment doubled after 15 years
Suppose we change the program so that the condition of the while loop is
while (balance <= targetBalance)
What is the effect on the program? Why?
int n = 1; while (n < 100) { n = 2 * n; System.out.print(n + " "); }
int years = 1; while (years <= 20) { double interest = balance * RATE / 100; balance = balance + interest; }
int years = 20; while (years > 0) { double interest = balance * RATE / 100; balance = balance + interest; years++; }
int years = 0; while (balance < targetBalance) { years++; balance = balance * (1 + RATE / 100); } System.out.println("The investment doubled after " + year + " years.");
int n = 1729; int sum = 0; while (n > 0) { int digit = n % 10; sum = sum + digit; n = n / 10; } System.out.println(sum);
int n = 5; while (n >= 0) { n--; System.out.print(n); }
n output54433221100 -1 -1
int n = 1; while (n <= 3) { System.out.print(n + ", "); n++; }
n outputThere is a comma after the last value. Usually, commas are between values only.11,21, 2,31, 2, 3, 4
int r = 1; int i = 1; while (i <= n) { r = r * a; i++; }
a n r i 2 41122438416 5
int n = 1; while (n != 50) { System.out.println(n); n = n + 10; }
n outputThis is an infinite loop. n is never equal to 50.11111121213131414151516161 ...
count = 1
temp = n
while (temp > 10)
Increment count.
Divide temp by 10.0.
Trace the pseudocode for n = 123 and n = 100. What error do you find?
count tempThis yields the correct answer. The number 123 has 3 digits.1123212.3 3 1.23
count tempThis yields the wrong answer. The number 100 also has 3 digits. The loop condition should have been while (temp >= 10).1100210.0
int counter = 1; // Initialize the counter while (counter <= 10) // Check the counter { System.out.println(counter); counter++; // Update the counter }
for (int counter = 1; counter <= 10; counter++) { System.out.println(counter); }
Figure 3 Execution of a for Loop
for (int counter = 10; counter >= 0; counter--) . . .
for (int counter = 0; counter <= 10; counter = counter + 2) . . .
for (int counter = 1; counter <= 10; counter++) { . . . } // counter no longer declared here
int counter;
for (counter = 1; counter <= 10; counter++)
{
. . .
}
// counter still declared here
for (int i = 0; i < str.length(); i++) { char ch = str.charAt(i); Process ch. }
for (int year = 1; year <= numberOfYears; year++) { Update balance. }
The balance after 20 years is 26532.98
int years = 1; while (years <= numberOfYears) { double interest = balance * rate / 100; balance = balance + interest; years++; }
for (int n = 10; n >= 0; n--) { System.out.println(n); }
Write a for loop that prints all even numbers between 10 and 20 (inclusive).
for (int i = 10; i <= 20; i = i + 2) { System.out.println(i); }
int sum = 0; for (int i = 1; i <= n; i++) { sum = sum + i; }
final int PERIODS = 5; for (int i = 1; i <= PERIODS; i++) { invest.waitYears(YEARS); System.out.printf( "The balance after %d years is %.2f\n", invest.getYears(), invest.getBalance()); }
int value; do { System.out.print("Enter an integer < 100: "); value = in.nextInt(); } while (value >= 100);
Suppose that we want to check for inputs that are at least 0 and at most 100. Modify the do loop for this check.
int value; do { System.out.print("Enter an integer < 100: "); value = in.nextInt(); } while (value >= 100);
do { System.out.print( "Enter a value between 0 and 100: "); value = in.nextInt(); } while (value < 0 || value > 100);
Rewrite the input check do loop using a while loop. What is the disadvantage of your solution?
int value; do { System.out.print("Enter an integer < 100: "); value = in.nextInt(); } while (value >= 100);
int value = 100; while (value >= 100) { System.out.print("Enter a value < 100: "); value = in.nextInt(); }Here, the variable value had to be initialized with an artificial value to ensure that the loop is entered at least once.
do { body } while (condition);
is equivalent to this while loop:
boolean first = true; while (first || condition) { body; first = false; }
int x; int sum = 0; do { x = in.nextInt(); sum = sum + x; } while (x != 0);
int x = 0; int previous; do { previous = x; x = in.nextInt(); sum = sum + x; } while (x != 0 && previous != x);
Enter salaries, -1 to finish: 10 10 40 -1 Average salary: 20
System.out.print("Enter salaries, -1 to finish: "); boolean done = false; while (!done) { value = in.nextDouble(); if (value == -1) { done = true; } else { Process value } }
System.out.print("Enter values, Q to quit: "); while (in.hasNextDouble()) { value = in.nextDouble(); Process value. }
What does the SentinelDemo.java program print when the user immediately types -1 when prompted for a value?
Why does the SentinelDemo.java program have two checks of the form salary != -1
What would happen if the declaration of the salary variable in SentinelDemo.java was changed to
double salary = -1;
System.out.print("Enter values, Q to quit: "); do { double value = in.nextDouble(); sum = sum + value; count++; } while (in.hasNextDouble());
Sometimes termination condition of a loop can only be evaluated in the middle of the loop. There are different approaches:
boolean done = false; while (!done) { String input = in.next(); if (input.equals("Q")) { done = true; } else { Process data. } }
Additional approaches:
while (!(input = in.next()).equals("Q")) { Process data. }
public void processInput(Scanner in) { while (true) { String input = in.next(); if (input.equals("Q")) { return; } Process data. } }
Storyboarding for a problem to convert units of measurement.
Storyboarding for a problem to convert units of measurement - part 2.
Provide a storyboard panel for a program that reads a number of test scores and prints the average score. The program only needs to process one set of scores. Don't worry about error handling.
Enter scores, Q to quit: 90 80 90 100 80 Q
The average is 88
(Program exits)
Google has a simple interface for converting units. You just type the question, and you get the answer.
Make storyboards for an equivalent interface in a Java program. Show a scenario in which all goes well, and show the handling of two kinds of errors.
Consider a modification of the program in Self Check 26. Suppose we want to drop the lowest score before computing the average. Provide a storyboard for the situation in which a user only provides one score.
Enter scores, Q to quit: 90 Q
Error: At least two scores are required.
(Program exits)
What is the problem with implementing the following storyboard in Java?
double total = 0; while (in.hasNextDouble()) { double input = in.nextDouble(); total = total + input; }
double total = 0;
int count = 0;
while (in.hasNextDouble())
{
double input = in.nextDouble();
total = total + input;
count++;
}
double average = 0;
if (count > 0)
{
average = total / count;
}
int spaces = 0; for (int i = 0; i < str.length(); i++) { char ch = str.charAt(i); if (ch == ' ') { spaces++; } }
int shortWords = 0; while (in.hasNext()) { String input = in.next(); if (input.length() <= 3) { shortWords++; } }
boolean found = false; char ch = '?'; int position = 0; while (!found && position < str.length()) { ch = str.charAt(position); if (ch == ' ') { found = true; } else { position++; } }
boolean valid = false; double input = 0; while (!valid) { System.out.print("Please enter a positive value < 100: "); input = in.nextDouble(); if (0 < input && input < 100) { valid = true; } else { System.out.println("Invalid input."); } }
double largest = in.nextDouble(); while (in.hasNextDouble()) { double input = in.nextDouble(); if (input > largest) { largest = input; } }
double smallest = in.nextDouble(); while (in.hasNextDouble()) { double input = in.nextDouble(); if (input < smallest) { smallest = input; } }
To find the height of the tallest bus rider, remember the largest value so far, and update it whenever you see a taller one.
double input = 0;
while (in.hasNextDouble())
{
double previous = input;
input = in.nextDouble();
if (input == previous)
{
System.out.println("Duplicate input");
}
}
double total = 0; while (in.hasNextDouble()) { double input = in.nextDouble(); if (input > 0) { total = total + input; } }
boolean found = false; for (int position = 0; !found && position < str.length(); position++) { char ch = str.charAt(position); if (ch == ' ') { found = true; } }
boolean found = false; int i = str.length() - 1; while (!found && i >= 0) { char ch = str.charAt(i); if (ch == ' ') { found = true; } else { i--; } }
double input = 0; boolean first = true; while (in.hasNextDouble()) { double previous = input; input = in.nextDouble(); if (first) { first = false; } else if (input == previous) { System.out.println("Duplicate input"); } }
x¹ | x² | x³ | x4 |
---|---|---|---|
1 | 1 | 1 | 1 |
2 | 4 | 8 | 16 |
3 | 9 | 27 | 81 |
Print table header. For x from 1 to 10 Print table row. Print new line.
For n from 1 to 4 Print xn.
1 2 3 4 x x x x 1 1 1 1 2 4 8 16 3 9 27 81 4 16 64 256 5 25 125 625 6 36 216 1296 7 49 343 2401 8 64 512 4096 9 81 729 6561 10 100 1000 10000
for (int i = 0; i < 3; i++) { for (int j = 0; j < 4; j++) { System.out.print(i + j); } System.out.println(); }
for (int i = 1; i <= 3; i++) { for (int j = 1; j <= 4; j++) { System.out.print("[]"); } System.out.println(); }
Method | Returns |
---|---|
nextInt(n) | A random integer between the integers 0 (inclusive) and n (exclusive) |
nextDouble() | A random floating-point number between 0 (inclusive) and 1 (exclusive) |
Random generator = new Random(); int d = 1 + generator.nextInt(6);
6 5 6 3 2 6 3 4 4 1
3 2 2 1 6 5 3 4 1 2
double r = generator.nextDouble(); // 0 <= r < 1 double x = -1 + 2 * r; // -1 <= x < 1
Estimate for pi: 3.1504
Die d1 = new Die(6); Die d2 = new Die(6);Then cast and print both of them:
System.out.println( d1.cast() + " " + d2.cast());
int sum = 2 + generator.nextInt(11);
int sum = generator.nextInt(6) + generator.nextInt(6) + 2;
generator.nextDouble() * 100.0
Figure 8
Stopping at a Breakpoint
Figure 9 Inspecting Variables
String input = in.next();
Word w = new Word(input);
int syllables = w.countSyllables();
System.out.println("Syllables in " + input + ": " + syllables);
String input = in.next();
Word w = new Word(input);
int syllables = w.countSyllables();
System.out.println("Syllables in " + input + ": " + syllables);
public int countSyllables()
{
int count = 0;
int end = text.length() - 1;
. . .
}