Presentation is loading. Please wait.

Presentation is loading. Please wait.

©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 1 Chapter 6: Iteration 1 Chapter 6 Iteration.

Similar presentations


Presentation on theme: "©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 1 Chapter 6: Iteration 1 Chapter 6 Iteration."— Presentation transcript:

1 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 1 Chapter 6: Iteration 1 Chapter 6 Iteration

2 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 2 Chapter 6: Iteration 2 while loop while (condition) statement; repeats the statement while the condition is true while (balance < 2 * initial) { year++; balance = balance + balance * rate / 100; }

3 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 3 Chapter 6: Iteration 3 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;

4 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 4 Chapter 6: Iteration 4 // 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."); }

5 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 5 Chapter 6: Iteration 5 Figure 1 Flowchart of a while Loop

6 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 6 Chapter 6: Iteration 6 Common Error: Infinite loops while (year < 20) { balance = balance + balance * rate / 100; } while (year > 0) { year++; // oops, meant --... } loop runs forever—must kill program

7 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 7 Chapter 6: Iteration 7 for loop for (init; condition; update) statement Example: for (i = 1; i 0; y--)... Equivalent to init; while (condition) { statement; update; }

8 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 8 Chapter 6: Iteration 8 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;

9 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 9 Chapter 6: Iteration 9 for (int year = 1; year <= NYEARS; year++) { double interest = balance * rate / 100; balance = balance + interest; System.out.println("year:” + year + ” balance: ” + balance); }

10 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 10 Chapter 6: Iteration 10 Figure 2 Flowchart of a for Loop

11 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 11 Chapter 6: Iteration 11 do loop do statement; while (condition); Executes the statement at least once Example: do { System.out.println("Interest rate:"); rate = Console.readDouble(); } while (rate <= 0);

12 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 12 Chapter 6: Iteration 12 Figure 3 Flowchart of a do Loop

13 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 13 Chapter 6: Iteration 13 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 <= ?

14 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 14 Chapter 6: Iteration 14 Off-by-1 errors Run through a simple example. initial balance = $100, interest rate 50% after one year: balance = $150 after two years: balance = $225  year must start at 0 interest rate 100% after one year: balance = $200 loop should stop  must use < Think, don't compile and try at random

15 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 15 Chapter 6: Iteration 15 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);

16 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 16 Chapter 6: Iteration 16 Nested loops Print table of powers x y 1 1 1 1 1 2 4 8 16 32 3 9 27 81 243... Print the rows for (int x = 0; x <= ROWS; x++) { print row // uses another loop }

17 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 17 Chapter 6: Iteration 17 Nested loops Loop inside a loop: for (int x = 0; x <= ROWS; x++) { for (int y = 0; y <= COLS; y++) { compute value print value } System.out.println(); } Count iterations: ROWS * COLS

18 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 18 Chapter 6: Iteration 18 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

19 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 19 Chapter 6: Iteration 19 String pstr = "” + p; // pad with spaces while (pstr.length() < COLUMN_WIDTH) pstr = ” ” + pstr; System.out.print(pstr); } System.out.println(); }

20 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 20 Chapter 6: Iteration 20 Reading a Set of Numbers boolean done = false; while (!done) { String line = console.readLine(); if (line == null) done = true; else process data } “Loop and a half”

21 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 21 Chapter 6: Iteration 21 Console input java Average 3.5 2.6 -1.2 Ctrl+D (Unix) or Ctrl-Z (DOS) Closes System.in Control character is not passed to program

22 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 22 Chapter 6: Iteration 22 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

23 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 23 Chapter 6: Iteration 23 Sentinels End of input marker that isn't part of the data set Example: java Sentinel1 3.5 2.6 1.2 0 Or better, use a non-numerical sentinel like Q

24 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 24 Chapter 6: Iteration 24 Sentinels boolean done = false; while (!done) { String line = console.readLine(); if (line is the sentinel) done = true; else process data }

25 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 25 Chapter 6: Iteration 25 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

26 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 26 Chapter 6: Iteration 26 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); }

27 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 27 Chapter 6: Iteration 27 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;

28 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 28 Chapter 6: Iteration 28 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); }

29 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 29 Chapter 6: Iteration 29 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

30 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 30 Chapter 6: Iteration 30 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); }

31 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 31 Chapter 6: Iteration 31 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 }

32 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 32 Chapter 6: Iteration 32 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

33 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 33 Chapter 6: Iteration 33 StringTokenizer tokenizer = new StringTokenizer(inputLine); while (tokenizer.hasMoreTokens()) { tokenizer.nextToken(); // read and discard count++; // count each word } System.out.println(count + "words"); }

34 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 34 Chapter 6: Iteration 34 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; }

35 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 35 Chapter 6: Iteration 35 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); }

36 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 36 Chapter 6: Iteration 36 Figure 6 The Buffon Needle Experiment

37 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 37 Chapter 6: Iteration 37 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();

38 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 38 Chapter 6: Iteration 38 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(); }

39 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 39 Chapter 6: Iteration 39 Figure 7 Variables in a Trial of the Buffon Needle Experiment

40 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 40 Chapter 6: Iteration 40 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();

41 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 41 Chapter 6: Iteration 41 // 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); }


Download ppt "©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 1 Chapter 6: Iteration 1 Chapter 6 Iteration."

Similar presentations


Ads by Google