LECTURE NOTES CHAPTER 7 REPETITION - repeatedly execute one or more statements WHILE LOOP while () - executes statement as long as condition is true - flowchart - statement can be a block statement - examples: while (!gameOver()) { currentPlayer.takeTurn(); if (currentPlayer == redPlayer) { currentPlayer = blackPlayer; } else { currentPlayer = redPlayer; } } DO LOOP do while (); - perform the body of the loop at least once - flowchart - not as common - can always be implemented as a while loop do System.out.println("Please enter an integer: "); while (!stdin.hasNextInt()); FOR LOOP int i = 0; while (i < 5) { System.out.print("i = " + i); i++; } for (; ; ) for (int i = 0; i < 5; i++) { System.out.println("i = " + i); } - initialize, test, and update a single variable - use when a variable runs from a starting to an ending value with a constant increment or decrement - flowchart - scope of variables defined in a for loop header limited to within loop - if need to use outside of the loop, must declare outside of the loop PROGRAMMING WITH LOOPS - infinite loop - program never stops - exit from containing method - commonly caused by - forgetting to update variable tested in the condition - updating the variable incorrectly for (int i = 1; i != 10; i++) { System.out.println(i); i++; } - off-by-one errors - solve by thinking through simple test cases - think about what each variable is supposed to represent through time - don't use != to test the end of a range, because it assumes something about the beginning of the range or the increment that may not be correct NESTED LOOPS - body of a loop is another loop - NestedLoops.java PROCESSING SENTINEL VALUES - sentinel value - used to indicate the end of a data set - not part of the data - be careful to choose something that couldn't be a real value - loop and a half - if termination condition can only be evaluated in the middle of a loop, use a boolean flag to control that loop boolean done = false; while (!done) { System.out.println("Input something: "); String input = stdin.nextLine(); if (input.equalsIgnoreCase("quit")) { done = true; } else { System.out.println(input); } } LOOP BOUNDS - symmetric bounds: equality on both sides - asymmetric bounds: one side equal but other side not - don't force symmetric - determine bounds - count iterations - easier with asymmetric bounds - i = a; i < b - executed b - a times - symmetric bounds - fence post error: fence with 10 sections has 11 posts - i = a; i <= b - executed b - a + 1 times - increment other than one - asymmetric: (b - a) / c - symmetric: (b - a) / c + 1 SIMULATIONS - generate events - evaluate outcome - frequently need randomized RANDOM - java.util.Random - pseudorandom number generator - methods - int nextInt(int n): 0 <= retval < n - double nextDouble(): 0 <= retval < 1