410 likes | 520 Vues
This chapter delves into iteration in Java programming, focusing on the use of while loops, for loops, and do loops. It covers how while loops execute statements as long as a condition remains true, and discusses potential pitfalls like infinite loops and off-by-one errors. The chapter also provides practical examples, demonstrating how to implement these loops to calculate compound interest and process input data. Additionally, it explains nested loops and their utility in complex tasks such as generating tables.
E N D
Chapter 6 Iteration
while loop • while (condition)statement; • repeats the statement while the condition is true • while (balance < 2 * initial){ year++; balance = balance + balance * rate / 100;}
Program DoubleInv.java public class DoubleInv { public static void main(String[] args) { ConsoleReader console = new ConsoleReader(System.in); System.out.println("Interest rate:"); double rate = console.readDouble(); System.out.println("Initial balance:"); double initialBalance = console.readDouble(); int year = 0; double balance = initialBalance;
// keep accumulating interest until balance doubles while (balance < 2 * initialBalance) { year++; double interest = balance * rate / 100; balance = balance + interest; } System.out.println("The investment doubled after " + year + ” years."); } }
Figure 1 Flowchart of a while Loop
Common Error: Infinite loops • while (year < 20){ balance = balance + balance * rate / 100; } • while (year > 0){ year++; // oops, meant -- . . .} • loop runs forever—must kill program
for loop • for (init; condition; update)statement • Example: for (i = 1; i <= 10; i++) ... for (y = 20; y > 0; y--) ... • Equivalent toinit;while (condition){ statement; update; }
Program Invest.java public class Invest { public static void main(String[] args) { ConsoleReader console = new ConsoleReader(System.in); System.out.println("Interest rate:"); double rate = console.readDouble(); final double INITIAL_BALANCE = 10000; final int NYEARS = 20; double balance = INITIAL_BALANCE;
for (int year = 1; year <= NYEARS; year++) { double interest = balance * rate / 100; balance = balance + interest; System.out.println("year:” + year + ” balance: ” + balance); } } }
Figure 2 Flowchart of a forLoop
do loop • dostatement;while (condition); • Executes the statement at least once • Example:do{ System.out.println("Interest rate:"); rate = Console.readDouble();} while (rate <= 0);
Figure 3 Flowchart of a doLoop
Off-by-1 errors • year = 0;while (balance < 2 * initial){ year++; balance = balance + balance * rate / 100;}System.out.println("Doubled after " + year + " years."); • Should year start at 0 or 1? • Should the test be < or <=?
Off-by-1 errors • Run through a simple example.initial balance = $100, interest rate 50%after one year: balance = $150after two years: balance = $225Þyear must start at 0 • interest rate 100%after one year: balance = $200loop should stop Þ must use < • Think, don't compile and try at random
Semicolon errors • A semicolon that shouldn't be there • sum = 0;for (i = 1; i <= 10; i++); sum = sum + i;System.out.println(sum); • A missing semicolon • for (i = 1; i <= 10; sum = sum + i++)System.out.println(sum);
Nested loops • Print table of powers xy 1 1 1 1 1 2 4 8 16 32 3 9 27 81 243 . . . • Print the rowsfor (int x = 0; x <= ROWS; x++){print row // uses another loop}
Nested loops • Loop inside a loop:for (int x = 0; x <= ROWS; x++){ for (int y = 0; y <= COLS; y++) {compute valueprint value}System.out.println();} • Count iterations: ROWS * COLS
Program Table.java public class Table { public static void main(String[] args) { final int COLUMN_WIDTH = 10; for (int x =1; x <= 10; x++) { // print table row for (int y = 1; y <= 8; y++) { int p = (int)Math.pow(x, y); // convert value to string
String pstr = "” + p; // pad with spaces while (pstr.length() < COLUMN_WIDTH) pstr = ” ” + pstr; System.out.print(pstr); } System.out.println(); } } }
Reading a Set of Numbers • boolean done = false;while (!done){ String line = console.readLine(); if (line == null) done = true; elseprocess data} • “Loop and a half”
Console input • java Average3.52.6-1.2Ctrl+D (Unix) or Ctrl-Z (DOS) • Closes System.in • Control character is not passed to program
Input/Output redirection • Put input in a file, say input.txt • java Average < input.txt • Now System.in reads from the file, not the keyboard • There is no Ctrl+D/Ctrl+Z character in the file • Can redirect output to a file:java MyProg > myfile.txt
Sentinels • End of input marker that isn't part of the data set • Example:java Sentinel13.52.61.20 • Or better, use a non-numerical sentinel like Q
Sentinels • boolean done = false;while (!done){ String line = console.readLine(); if (line is the sentinel) done = true; elseprocess data}
Program Average.java public class Average { public static void main(String[] args) { ConsoleReader console = new ConsoleReader(System.in); System.out.println("Enter data."); double sum = 0; int count = 0; // compute sum of all input values
boolean done = false; while (!done) { String inputLine = console.readLine(); if (inputLine == null) done = true; else { double x = Double.parseDouble(inputLine); sum = sum + x; count++; } } // compute average if (count == 0) System.out.println("No data"); else System.out.println("Average = ” + sum / count); } }
Program Sentinel1.java public class Sentinel1 { public static void main(String[] args) { ConsoleReader console = new ConsoleReader(System.in); System.out.println("Enter data (0 to finish):"); double sum = 0; int count = 0; // compute sum of all input values boolean done = false;
while (!done) { String inputLine = console.readLine(); double x = Double.parseDouble(inputLine); if (x == 0) done = true; else { sum = sum + x; count++; } } // compute average if (count == 0) System.out.println("No data"); else System.out.println("Average = ” + sum / count); } }
Program Sentinel2.java public class Sentinel2 { public static void main(String[] args) { ConsoleReader console = new ConsoleReader(System.in); System.out.println("Enter data (Q to finish):"); double sum = 0; int count = 0; // compute sum of all input values
boolean done = false; while (!done) { String inputLine = console.readLine(); if (inputLine.equalsIgnoreCase("Q")) done = true; else { double x = Double.parseDouble(inputLine); sum = sum + x; count++; } } // compute average if (count == 0) System.out.println("No data"); else System.out.println("Average = ” + sum / count); } }
String tokenization • Break up string into tokens (words delimited by white space) • StringTokenizer tokenizer = new StringTokenizer();while (tokenizer.hasMoreTokens()){ String token = tokenizer.nextToken();process token}
Program Words.java import java.util.StringTokenizer; public class Words { public static void main(String[] args) { ConsoleReader console = new ConsoleReader(System.in); System.out.println("Enter Words:"); int count = 0; boolean done = false; while (!done) { String inputLine = console.readLine(); if (inputLine == null) done = true; else { // break up input line into words
StringTokenizer tokenizer = new StringTokenizer(inputLine); while (tokenizer.hasMoreTokens()) { tokenizer.nextToken(); // read and discard count++; // count each word } } } System.out.println(count + "words"); } }
Traversing characters in a string • char: character type—a single Unicode character • Character constants use single quotes: 'A', '\u00E9' • 'A'is not the same as "A" • String s = . . .;for (int i = 0; i < s.length(); i++){ char ch = s.charAt(i);process ch;}
Program Reverse.java public class Reverse { public static void main(String[] args) { ConsoleReader console = new ConsoleReader(System.in); System.out.println("Please enter a string:"); String s = console.readLine(); String r = ""; for (int i = 0; i < s.length(); i++) { char ch = s.charAt(i); r = ch + r; // add ch in front } System.out.println(s + ” reversed is ” + r); } }
Figure 6 The Buffon Needle Experiment
Simulations • Random numbers:Random generator = new Random();int n = generator.nextInt(CHOICES);double x = generator.nextDouble(); • Throw die (random number between 1 and 6)int d = 1 + generator.nextInt(6); • Buffon needle: simulate needle throw double ylow = 2*generator.nextDouble();double angle = 180*generator.nextDouble();
Program Dice.java import java.util.Random; public class Dice { public static void main(String[] args) { Random generator = new Random(); // roll dice ten times for (int i = 1; i <= 10; i++) { int d = 1 + generator.nextInt(6); System.out.print(d + ” "); } System.out.println(); } }
Figure 7 Variables in a Trial of the Buffon Needle Experiment
Program Buffon.java import java.util.Random; public class Buffon { public static void main(String[] args) { Random generator = new Random(); int hits = 0; final int NTRIES = 10000; for (int i = 1; i <= NTRIES; i++) { // simulate needle throw double ylow = 2 * generator.nextDouble(); double angle = 180 * generator.nextDouble();
// compute high point of needle double yhigh = ylow + Math.sin(Math.toRadians(angle)); if (yhigh >= 2) hits++; } // print approximation of PI System.out.println("Tries / Hits = " + (NTRIES * 1.0) / hits); } }