©2000, john wiley & sons, inc. horstmann/java essentials, 2/e 1 chapter 6: iteration 1 chapter...

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

Upload: hugo-mckinney

Post on 17-Dec-2015

219 views

Category:

Documents


5 download

TRANSCRIPT

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

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

1

Chapter 6: Iteration1

Chapter 6

Iteration

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

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

2

Chapter 6: Iteration2

while loop

• while (condition) statement;

• repeats the statement while the condition is true• while (balance < 2 * initial){ year++; balance = balance + balance * rate / 100;}

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

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

3

Chapter 6: Iteration3

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;

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

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

4

Chapter 6: Iteration4

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

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

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

5

Chapter 6: Iteration5

Figure 1Flowchart of a while Loop

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

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

6

Chapter 6: Iteration6

Common Error: Infinite loops

• while (year < 20){ balance = balance + balance * rate / 100; }

• while (year > 0){ year++; // oops, meant -- . . .}

• loop runs forever—must kill program

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

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

7

Chapter 6: Iteration7

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

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

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

8

Chapter 6: Iteration8

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;

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

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

9

Chapter 6: Iteration9

for (int year = 1; year <= NYEARS; year++) { double interest = balance * rate / 100; balance = balance + interest; System.out.println("year:” + year + ” balance: ” + balance); } }}

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

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

10

Chapter 6: Iteration10

Figure 2Flowchart of a for Loop

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

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

11

Chapter 6: Iteration11

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);

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

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

12

Chapter 6: Iteration12

Figure 3Flowchart of a do Loop

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

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

13

Chapter 6: Iteration13

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 <=?

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

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

14

Chapter 6: Iteration14

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

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

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

15

Chapter 6: Iteration15

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);

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

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

16

Chapter 6: Iteration16

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}

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

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

17

Chapter 6: Iteration17

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

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

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

18

Chapter 6: Iteration18

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

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

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

19

Chapter 6: Iteration19

String pstr = "” + p; // pad with spaces

while (pstr.length() < COLUMN_WIDTH) pstr = ” ” + pstr;

System.out.print(pstr); } System.out.println(); } }}

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

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

20

Chapter 6: Iteration20

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”

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

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

21

Chapter 6: Iteration21

Console input

• java Average3.52.6-1.2Ctrl+D (Unix) or Ctrl-Z (DOS)

• Closes System.in• Control character is not passed to program

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

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

22

Chapter 6: Iteration22

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

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

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

23

Chapter 6: Iteration23

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

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

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

24

Chapter 6: Iteration24

Sentinels

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

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

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

25

Chapter 6: Iteration25

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

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

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

26

Chapter 6: Iteration26

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

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

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

27

Chapter 6: Iteration27

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;

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

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

28

Chapter 6: Iteration28

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

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

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

29

Chapter 6: Iteration29

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

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

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

30

Chapter 6: Iteration30

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

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

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

31

Chapter 6: Iteration31

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}

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

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

32

Chapter 6: Iteration32

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

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

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

33

Chapter 6: Iteration33

StringTokenizer tokenizer = new StringTokenizer(inputLine); while (tokenizer.hasMoreTokens()) { tokenizer.nextToken(); // read and discard count++; // count each word } } }

System.out.println(count + "words"); }}

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

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

34

Chapter 6: Iteration34

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

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

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

35

Chapter 6: Iteration35

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

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

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

36

Chapter 6: Iteration36

Figure 6The Buffon NeedleExperiment

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

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

37

Chapter 6: Iteration37

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();

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

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

38

Chapter 6: Iteration38

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(); }}

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

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

39

Chapter 6: Iteration39

Figure 7Variables in a Trial ofthe Buffon NeedleExperiment

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

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

40

Chapter 6: Iteration40

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();

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

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

41

Chapter 6: Iteration41

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