1 / 41

Chapter 6

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

erwin
Download Presentation

Chapter 6

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 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. 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. // 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. Figure 1 Flowchart of a while Loop

  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. 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; }

  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. for (int year = 1; year <= NYEARS; year++) { double interest = balance * rate / 100; balance = balance + interest; System.out.println("year:” + year + ” balance: ” + balance); } } }

  10. Figure 2 Flowchart of a forLoop

  11. do loop • dostatement;while (condition); • Executes the statement at least once • Example:do{ System.out.println("Interest rate:"); rate = Console.readDouble();} while (rate <= 0);

  12. Figure 3 Flowchart of a doLoop

  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. 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

  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. 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}

  17. 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

  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. String pstr = "” + p; // pad with spaces while (pstr.length() < COLUMN_WIDTH) pstr = ” ” + pstr; System.out.print(pstr); } System.out.println(); } } }

  20. 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”

  21. Console input • java Average3.52.6-1.2Ctrl+D (Unix) or Ctrl-Z (DOS) • Closes System.in • Control character is not passed to program

  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. 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

  24. Sentinels • boolean done = false;while (!done){ String line = console.readLine(); if (line is the sentinel) done = true; elseprocess data}

  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. 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. 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. 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. 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. 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. 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. 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. StringTokenizer tokenizer = new StringTokenizer(inputLine); while (tokenizer.hasMoreTokens()) { tokenizer.nextToken(); // read and discard count++; // count each word } } } System.out.println(count + "words"); } }

  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. 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. Figure 6 The Buffon Needle Experiment

  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. 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. Figure 7 Variables in a Trial of the Buffon Needle Experiment

  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. // 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); } }

More Related