Presentation is loading. Please wait.

Presentation is loading. Please wait.

Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Designing with While loops.

Similar presentations


Presentation on theme: "Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Designing with While loops."— Presentation transcript:

1 Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Designing with While loops COMP 102 #11 2013

2 © Peter Andreae COMP102 11:2 Menu Repetition counted loops loops for input using break Administrivia: Working with other students! You must both declare it labs and help desks next week…..

3 © Peter Andreae COMP102 11:3 Repetition / Iteration Doing some action repeatedly: “Vacuum the floor until it is clean” “keep watching until midnight” go on handing out tickets as long as there are any people waiting around” “polish each of the cups on the shelf” Common features: An action to repeat Some condition for when to keep going/when to stop

4 © Peter Andreae COMP102 11:4 Repetion/Iteration in Java LDC 4.5 Several different ways of specifying repetition. One of the simplest is with the while statement: while ( condition ) { actions to perform each time round } while ( true ) { UI.println("this repeats forever!"); } int n = 1; while ( n <= 100) { UI.println(n) ; n = n + 1; } Similar structure to the if statement

5 © Peter Andreae COMP102 11:5 While syntax Meaning: As long as the condition is still true, repeat the actions one more time Stop once the condition is false. Don’t do it at all if condition is initially false Similar to if, but keeps repeating the actions, as long as the condition is still true each time round no else — just skips to next statement when condition is false while(condition) actions { }

6 © Peter Andreae COMP102 11:6 While with numbers #1 Print a table of numbers and their squares: public void printTable(int max){ int num = 1; while ( num <= max ) { UI.printf(“ %3d %6d \n”, num, (num*num)); num = num + 1; } } Repetition generally involves initialisation:get ready for the loop test:whether to repeat body:what to repeat “increment”:get ready for the next iteration Initialise Body Test Increment

7 © Peter Andreae COMP102 11:7 While with numbers #2 Counting down: public void countDown(int start){ int count = start; while ( count >= 1) { UI.println( count ); count = count – 1; } UI.println(“ GO”); } : this.countDown(5); :

8 © Peter Andreae COMP102 11:8 Nested loops: while inside while public void drawCircles(int rows, int cols) { int row = 0; while (row < rows) { int diam = 20; col = 0; while ( col < cols ) { int x = 50 + row*diam; int y = 20 +col*diam; canvas.fillOval(x, y, diam, diam); col++; } row++; }

9 © Peter Andreae COMP102 11:9 Reading multiple values from user To ask user for a single value: UI.askString("Enter name: ") UI.askInt("How old are you: ") UI.askDouble("How tall are you: ") To ask for a series of values: UI.print("Enter all the marks: "); double sum = 0; while (….) { sum = sum + UI.nextDouble(); } next(), nextInt(), nextLine(), nextDouble() read and return the next value without further prompting. 45 27.5 49 35.5 31 40 42.5 36 21 25 29.5

10 © Peter Andreae COMP102 11:10 Determining when the user is done Can't just read to the end – the user may still be typing  the program will always wait for input if there is none there Can end at a special value UI.print("Enter all the marks (end with -1): "); double sum = 0; double n = UI.nextDouble( ); while ( n != -1 ) { sum = sum + n; n = UI.nextDouble(); } If reading numbers, can end at a non-number: UI.print("Enter all the marks (end with 'done'): "); double sum = 0; while ( UI.hasNextDouble()) { sum = sum + UI.nextDouble(); } 45 27.5 49 35.5 -1 45 27.5 49 35.5 done

11 © Peter Andreae COMP102 11:11 While with input from user Read numbers from user and count how many 10’s: public void count7s( ){ UI.print(“Enter numbers (‘q’ to quit): ”); int count = 0; while ( UI.hasNextInt( ) ) { int n = UI.nextInt(); if ( n == 10 ) { count = count + 1; } } UI.printf(“There were %d occurrences of 10\n”, count); } What happened to the 'q'? Initialise body test

12 © Peter Andreae COMP102 11:12 Reading words from user public void countWordsBeforeThe( ) { int count = 0; UI.print("Enter some words: ”); // loop, stopping when you get to 'the' // read next token // increment count UI.printf(“You had %d words before 'the'.", count); }

13 © Peter Andreae COMP102 11:13 Reading words from user: BAD public void countWordsBeforeThe( ) { int count = 0; UI.print("Enter some words: ”); while ( ! word.equalsIgnoreCase("the”) ) { String word = UI.next(); count = count + 1; } UI.printf(“You had %d words before 'the'.", count); } Too late for the condition!!!

14 © Peter Andreae COMP102 11:14 Reading words from user: BAD public void countWordsBeforeThe( ) { int count = 0; UI.print("Enter some words: ”); String word = UI.next(); while ( ! word.equalsIgnoreCase("the”) ) { count = count + 1; } UI.printf(“You had %d words before 'the'.", count); } never reads the next word !!!

15 © Peter Andreae COMP102 11:15 Reading words from user: Fixed public void countWordsBeforeThe( ) { int count = 0; UI.print("Enter some words: ”); String word = UI.next(); while ( ! word.equalsIgnoreCase("the”) ) { count = count + 1; word = UI.next(); } UI.printf(“You had %d words before 'the'.", count); } read next word at end of loop ("increment") read first word before loop

16 © Peter Andreae COMP102 11:16 Alternate design: using break. public void countWordsBeforeThe( ) { int count = 0; UI.print("Enter some words: ”); while ( true ) { String word = UI.next(); if ( word.equalsIgnoreCase("the”) ){ break; } count = count + 1; } UI.printf(“You had %d words before 'the'.", count); } Note: Textbook does not like this style; I do Only use when the test has to be in the middle of the loop Typically only use with a while (true) {….. The condition is an exit condition, not a keep going condition gets out of the enclosing while loop

17 © Peter Andreae COMP102 11:17 Designing loops Is the number of steps determined at the beginning? int i = 0;int i = 1; while ( i < number) {while ( i <= number) {  do actions 〉 i = i + 1;i++;} Note, can count from 0 or from 1! Otherwise 〈 intialise 〉 while ( 〈 condition-to-do it again 〉 ) { 〈 body 〉 〈 increment 〉 } Shorthand for i = i+1

18 © Peter Andreae COMP102 11:18 Designing loops Does exiting the loop depend on the actions? if soor set up for the test while ( true ) { while ( test ) {set up for the test do actionsif ( exit-test ) { set up for the next test break; } do actions } Write out the steps for a couple of iterations including the tests to determine when to quit/keep going Identify the section that is repeated preferably starting with the test Wrap it with a while ( ) { } Identify the condition for repeating.

19 © Peter Andreae COMP102 11:19 More loops with user input Make user guess a magic word: prompt user for a word test if it is “pumpkin” if not, try again UI.print(“Please enter the magic word:”); String answer = UI.next(); if ( answer.equalsIgnoreCase(“pumpkin”) ) if not, go back where to?? at end UI.println(“You finally guessed it!”);

20 © Peter Andreae COMP102 11:20 Magic word 1: break to exit Put “while” at the beginning of the repeated section Use the “infinite loop” and an if ( ) { break; } while ( true ) { UI.print(“Please enter the magic word:”); String answer = UI.next(); if ( answer.equalsIgnoreCase(“pumpkin”) ) { break; } UI.println(“You finally guessed it!”);

21 © Peter Andreae COMP102 11:21 Magic word 2: unfold Put “while” where the test is, Repeat the “set up” in the body. Scanner sc = new Scanner(System.in); UI.print(“Please enter the magic word:”); String answer = sc.next(); while ( ! answer.equalsIgnoreCase(“pumpkin”) ) { UI.print(“Please enter the magic word:”); answer = sc.next(); } UI.println(“You finally guessed it!”);

22 © Peter Andreae COMP102 11:22 Magic word 3: clever initialisation Set up a “dummy” case first. Scanner sc = new Scanner(System.in); String answer = “ ”; while ( ! answer.equalsIgnoreCase(“pumpkin”) ) { UI.print(“Please enter the magic word:”); answer = scan.next(); } UI.println(“You finally guessed it!”);


Download ppt "Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Designing with While loops."

Similar presentations


Ads by Google