1 / 89

Chapter Topics

Chapter Topics. Chapter 4 discusses the following main topics: The Increment and Decrement Operators The while Loop Using the while Loop for Input Validation The do - while Loop The for Loop Running Totals and Sentinel Values. Chapter Topics.

kdansby
Download Presentation

Chapter Topics

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 Topics Chapter 4 discusses the following main topics: The Increment and Decrement Operators The while Loop Using the while Loop for Input Validation The do-while Loop The for Loop Running Totals and Sentinel Values

  2. Chapter Topics Chapter 4 discusses the following main topics: Nested Loops The break and continue Statements Deciding Which Loop to Use Introduction to File Input and Output Generating Random Numbers with the Random class

  3. The Increment and Decrement Operators There are numerous times where a variable must simply be incremented or decremented. number = number + 1; number = number – 1; Java provide shortened ways to increment and decrement a variable’s value. Using the ++ or -- unary operators, this task can be completed quickly. number++; or ++number; number--; or --number; Example: IncrementDecrement.java

  4. The Increment and Decrement Operators int sum = 100, num = 10; String strSumNum = "sum = %d and num = %d. "; System.out.printf("\n\nIntially " + strSumNum, sum, num); sum = sum + ++num; System.out.printf("\n" + strSumNum, sum, num); sum = ++num + sum; System.out.printf("\n" + strSumNum, sum, num); sum = 100; num = 10; System.out.printf("\nIntially " + strSumNum, sum, num); sum = sum + num++; System.out.printf("\n" + strSumNum, sum, num); sum = num++ + sum; System.out.printf("\n" + strSumNum, sum, num);

  5. The Increment and Decrement Operators int sum = 100, num = 10; String strSumNum = "sum = %d and num = %d. "; System.out.printf("\n\nIntially " + strSumNum, sum, num); sum = sum + ++num; System.out.printf("\n" + strSumNum, sum, num); sum = ++num + sum; System.out.printf("\n" + strSumNum, sum, num); sum = 100; num = 10; System.out.printf("\nIntially " + strSumNum, sum, num); sum = sum + num++; System.out.printf("\n" + strSumNum, sum, num); sum = num++ + sum; System.out.printf("\n" + strSumNum, sum, num); Intially sum = 100 and num = 10. sum = 111 and num = 11. sum = 123 and num = 12. Intially sum = 100 and num = 10. sum = 110 and num = 11. sum = 121 and num = 12.

  6. The Increment and Decrement Operators int number = 0; String strInitNum = "Initial value of number is %d.\n"; System.out.printf(strInitNum, number); String strNum2Plus = "number++ is %d.\n"; String strNum2Minus = "number-- is %d.\n"; String str2PlusNum = "++number is %d.\n"; String str2MinusNum = "--number is %d.\n"; number++; System.out.printf(strNum2Plus, number); number--; System.out.printf(strNum2Minus, number); System.out.printf(strNum2Plus, number++); System.out.printf(strNum2Minus, number--); System.out.printf("The final value of number is %d.\n", number);

  7. The Increment and Decrement Operators int number = 0; String strInitNum = "Initial value of number is %d.\n"; System.out.printf(strInitNum, number); String strNum2Plus = "number++ is %d.\n"; String strNum2Minus = "number-- is %d.\n"; String str2PlusNum = "++number is %d.\n"; String str2MinusNum = "--number is %d.\n"; number++; System.out.printf(strNum2Plus, number); number--; System.out.printf(strNum2Minus, number); System.out.printf(strNum2Plus, number++); System.out.printf(strNum2Minus, number--); System.out.printf("The number storage has %d.\n", number); Initial value of number is 0. number++ is 1. number-- is 0. number++ is 0. number-- is 1. The number storage has 0.

  8. The Increment and Decrement Operators number = 0; System.out.printf(strInitNum, number); ++number; System.out.printf(str2PlusNum , number); --number; System.out.printf(str2MinusNum, number); System.out.printf(str2PlusNum , ++number); System.out.printf(str2MinusNum, --number); System.out.printf("The number storage has %d.\n", number); Initial value of number is 0. ++number is 1. --number is 0. ++number is 1. --number is 0. The number storage has 0.

  9. Differences Between Prefix and Postfix When an increment or decrement are the only operations in a statement, there is no difference between prefix and postfix notation. e.g., num++; ++num; nos--; -- nos; When used in an expression: prefix notation indicates that the variable will be incremented or decremented prior to the rest of the equation being evaluated. e.g., sum = sum + ++num; sum = ++num + sum; postfix notation indicates that the variable will be incremented or decremented after the rest of the equation has been evaluated. e.g., sum = sum + num++; sum = num++ + sum; Example: Prefix.java

  10. intsum = 10; intnum = 1; sum = sum + ++num; System.out.println("sum is " + sum + ". num is " + num); sum = 10; num = 1; sum = ++num + sum; System.out.println("sum is " + sum + ". num is " + num); sum = 10; num = 1; sum = sum + num++; System.out.println("sum is " + sum + ". num is " + num); sum = 10; num = 1; sum = num++ + sum; System.out.println("sum is " + sum + ". num is " + num); sum is 12. num is 2 sum is 12. num is 2 sum is 11. num is 2 sum is 11. num is 2

  11. int sum = 10; int num = 1; sum = sum + --num; System.out.println("sum is " + sum + ". num is " + num); sum = 10; num = 1; sum = --num + sum; System.out.println("sum is " + sum + ". num is " + num); sum = 10; num = 1; sum = sum + num--; System.out.println("sum is " + sum + ". num is " + num); sum = 10; num = 1; sum = num-- + sum; System.out.println("sum is " + sum + ". num is " + num); sum is 10. num is 0 sum is 10. num is 0 sum is 11. num is 0 sum is 11. num is 0

  12. Differences Between Prefix and Postfix int sum = number = 0; sum = sum + ++number; //number=number+1; sum=sum+number; System.out.printf("Sum is %d.\n", sum); sum = number = 0; sum = ++number + sum; //number=number+1; sum=sum+number; System.out.printf("Sum is %d.\n", sum); sum = number = 0; sum = sum + number++; //sum=sum+number; number=number+1; System.out.printf("Sum is %d.\n", sum); System.out.printf("The number storage has %d.\n", number); sum = number = 0; sum = number++ + sum; //sum = number + sum; number=number+1; System.out.printf("Sum is %d.\n", sum); System.out.printf("The number storage has %d.\n", number); Sum is 1. Sum is 1. Sum is 0. The number storage has 1. Sum is 0. The number storage has 1.

  13. The while Loop Java provides three different looping structures. The while loop has the form: while(condition) { statements; } While the condition is true, the statements will execute repeatedly. The while loop is a pretest loop, which means that it will test the value of the condition prior to executing the loop. f C t S int x = 0, y = 3; while( x <= y) { x = x + 1; y = y – 1; } System.out.printf(“x is %d and y is %d.\n”, x, y); Result is: x is 2 and y is 1.

  14. intx = 0, y = 3; while( x <= y) { x = x + 2; y = y - 1; System.out.printf("x is %d and y is %d.\n", x, y); } System.out.printf("x is %d and y is %d.\n", x, y); x is 2 and y is 2. x is 4 and y is 1. x is 4 and y is 1.

  15. The while Loop Care must be taken to set the condition to false somewhere in the loop so the loop will end. Loops that do not end are called infinite loops. A while loop executes 0 or more times. If the condition is false, the loop will not execute. Example: WhileLoop.java int x = 0, y = 3; while( x > y) { x = x + 1; y = y – 1; System.out.println(“I was here!”); } System.out.printf(“x is %d and y is %d.\n”, x, y); Result is: x is 0 and y is 3.

  16. The while loop Flowchart boolean expression? false true statement(s) while (Boolean expression) { statements; }

  17. Infinite Loops In order for a while loop to end, the condition must become false. The following loop will not end: int x = 20; while(x > 0) { System.out.println("x is greater " + "than 0"); String str = “x = %d is greater than 0.\n”; System.out.printf(str, x) } The variable x never gets decremented so it will always be greater than 0. Adding the x-- above fixes the problem.

  18. Infinite Loops This version of the loop decrements x during each iteration: int x = 20; while(x > 0) { System.out.println("x is greater " + "than 0"); String str = “x = %d is greater than 0.\n”; System.out.printf(str, x); x--; }

  19. Block Statements in Loops Curly braces are required to enclose block statement while loops. (like block if statements) while (condition) { statement; statement; … statement; }

  20. Block Statements in Loops Curly braces are required to enclose block statement while loops. (like block if statements) int c = 3; while (c > 0) c = c - 1; System.out.printf("c is %d.\n", c); c = 3; while (c > 0) { c = c - 1; System.out.printf("c is %d.\n", c); } c is 0. c is 2. c is 1. c is 0.

  21. The while Loop for Input Validation Input validation is the process of ensuring that user input is valid. Scanner keyboard = new Scanner(System.in); System.out.print("Enter a number in the " + "range of 1 through 100: "); number = keyboard.nextInt(); // Validate the input. while (number < 1 || number > 100) { System.out.println("That number is invalid."); System.out.print("Enter a number in the " + "range of 1 through 100: "); number = keyboard.nextInt(); } System.out.println(“A number is “ + number + "."); Example: SoccerTeams.java

  22. The while Loop for Input Validation Input validation is the process of ensuring that user input is valid. Scanner keyboard = new Scanner(System.in); System.out.print("Enter a number in the " + "range of 1 through 100: "); number = keyboard.nextInt(); // Validate the input. while (number < 1 || number > 100) { System.out.println("That number is invalid."); System.out.print("Enter a number in the " + "range of 1 through 100: "); number = keyboard.nextInt(); } System.out.println(“A number is “ + number + "."); Example: SoccerTeams.java Enter a number in the range of 1 through 100: 101 That number is invalid. Enter a number in the range of 1 through 100: -1 That number is invalid. Enter a number in the range of 1 through 100: 51 A number is 51.

  23. The do-while Loop The do-while loop is a post-test loop, which means it will execute the loop prior to testing the condition. The do-while loop (sometimes also called a do loop) takes the form: do { statement(s); } while (condition); Example: TestAverage1.java

  24. The do-while Loop Flowchart statement(s) true boolean expression? false do { statement(s); } while (boolean expression);

  25. The for Loop The for loop is a pre-test loop. The for loop allows the programmer to initialize a control variable, test a condition, and modify the control variable all in one line of code. The for loop takes the form: for(initialization; test; update) { statement(s); } See example: Squares.java

  26. The for Loop Flowchart false boolean expression? true statement(s) update for(initialization; test; update) { statement(s); } initialization Is for Loop the same as the while Loop? initialization; while (test) { statement(s); update; }

  27. The Sections of The for Loop The initialization sectionof the for loop allows the loop to initialize its own control variable. The test sectionof the for statement acts in the same manner as the condition section of a while loop. The update sectionof the for loop is the last thing to execute at the end of each loop. Example: UserSquares.java for (inti = 0; i < 5; i++) { System.out.println(i); } //System.out.println(i); //i is undefined here! int j = 0; do { System.out.println(j); j++; }while (j < 5); System.out.println(j); int k = 0; while (k < 5) { System.out.println(k); k++; } System.out.println(k); 0 1 2 3 4 0 1 2 3 4 j is 5 0 1 2 3 4 k is 5

  28. What are the differences among for statement, do-while statement and while statement? See the next two slides.

  29. Enter an integer as an index: 5 for loop has an output: 5 do while has an output: 5 while has an output: 5 package chapter04; import java.util.Scanner; publicclass Chapter04 { publicstaticvoid main(String[] args) { Scanner kbInput = new Scanner(System.in); System.out.println("Enter an integer as an index: "); intindexReserved = kbInput.nextInt(); intindex = indexReserved; for ( ; index >= 5; index--) { System.out.println("for loop has an output: " + index); } //end of for index = indexReserved; do { System.out.println("do while has an output: " + index); index--; } while (index >= 5); index = indexReserved; while (index >= 5 ) { System.out.println("while has an output: " + index); index--; } //end of while } //end of main } Enter an integer as an index: 0 do while has an output: 0

  30. Scope of the variable iindex; for (intiindex=6 ; iindex >= 5; iindex--) { System.out.println("for loop has an output: " + iindex); } System.out.println("for loop has an output: " + iindex); Exception in thread "main" java.lang.Error: Unresolved compilation problem: iindex cannot be resolved to a variable int iindex; for (iindex=6 ; iindex >= 5; iindex--) { System.out.println("for loop has an output: " + iindex); } System.out.println("for loop has an output: " + iindex);

  31. Scope of the variable iindex; int iindex; for (iindex=6 ; iindex >= 5; iindex--) { System.out.println("for loop has an output: " + iindex); } System.out.println("for loop has an exit output: " + iindex); for loop has an output: 6 for loop has an output: 5 for loop has an exit output: 4

  32. The Sections of The for Loop The initialization sectionof the for loop allows the loop to initialize its own control variable. The test sectionof the for statement acts in the same manner as the condition section of a while loop. The update sectionof the for loop is the last thing to execute at the end of each loop. Example: UserSquares.java

  33. The for Loop Initialization The initialization section of a for loop is optional; however, it is usually provided. Typically, for loops initialize a counter variable that will be tested by the test section of the loop and updated by the update section. The initialization section can initialize multiple variables. Variables declared in this section have scope only for the for loop. for (inti = 0; i < 5; i++) { System.out.println(i); } System.out.println(i); //i is undefined here!

  34. The for Loop Initialization The initialization section of a for loop is optional; however, it is usually provided. Typically, for loops initialize a counter variable that will be tested by the test section of the loop and updated by the update section. The initialization section can initialize multiple variables. Variables declared in this section have scope only for the for loop. for (inti = 0; i < 5; i++) { System.out.println(i); } //System.out.println(i); //i is undefined here! intc = 0; for (; c < 5; c++) { System.out.println(c); } System.out.println(c); //i is undefined here! 0 1 2 3 4 0 1 2 3 4 5

  35. The Update Expression The update expression is usually used to increment or decrement the counter variable(s) declared in the initialization section of the for loop. The update section of the loop executes last in the loop. The update section may update multiple variables. Each variable updated is executed as if it were on a line by itself.

  36. Modifying The Control Variable You should avoid updating the control variable of a for loop within the body of the loop. The update section should be used to update the control variable. Updating the control variable in the for loop body leads to hard to maintain code and difficult debugging.

  37. Multiple Initializations and Updates for (int x = 0, y = -1; (x < 3 || y < 3); x++, y++) { System.out.printf("x = %d and y = %d.\n", x, y); } //System.out.printf("x = %d and y = %d.\n", x, y); //x and y cannot be resolved to variable int x, y; for (x = 0, y = -1; (x < 3 || y < 3); x++, y++) { System.out.printf("x = %d and y = %d.\n", x, y); } System.out.printf("Outside for loop: x = %d and y = %d.\n", x, y);

  38. Multiple Initializations and Updates for (int x = 0, y = -1; (x < 3 || y < 3); x++, y++) { System.out.printf("x = %d and y = %d.\n", x, y); } //System.out.printf("x = %d and y = %d.\n", x, y); //x and y cannot be resolved to a variable int x, y; for (x = 0, y = -1; (x < 3 || y < 3); x++, y++) { System.out.printf("x = %d and y = %d.\n", x, y); } System.out.printf("Outside for loop: x = %d and y = %d.\n", x, y); x = 0 and y = -1. x = 1 and y = 0. x = 2 and y = 1. x = 3 and y = 2. x = 0 and y = -1. x = 1 and y = 0. x = 2 and y = 1. x = 3 and y = 2. Outside for loop: x = 4 and y = 3.

  39. int x1 = 100, y1 = 99; for (int x1 = 0, y1 = -1; (x1 < 3 && y1 < 3); x1++, y1++) { System.out.printf("x1 = %d and y1 = %d.\n", x1, y1); } System.out.printf("Outside for loop:\n" + "x1 = %d and y1 = %d.\n", x1, y1); Exception in thread "main" java.lang.Error: Unresolved compilation problems: Duplicate local variable x1 Duplicate local variable y1 at forStmtCh04_01.Demos_ForStmt.main(Demos_ForStmt.java:15)

  40. Running Totals Loops allow the program to keep running totals while evaluating data. Imagine needing to keep a running total of user input. Example: TotalSales.java

  41. Logic for Calculating a Running Total Set accumulator to 0 Is there another number to read? No (false) Yes (true) Read the next number Add the number to the accumulator

  42. Logic for Calculating a Running Total

  43. Sentinel Values Sometimes the end point of input data is not known. A sentinel value can be used to notify the program to stop acquiring input. If it is a user input, the user could be prompted to input data that is not normally in the input data range (i.e. –1 where normal input would be positive.) Programs that get file input typically use the end-of-file marker to stop acquiring input data. Example: SoccerPoints.java

  44. import javax.swing.JOptionPane; publicclass TotalSales { publicstaticvoid main(String[] args) { doublesumNumbers = 0; final inttotalNumbers; doublenumber; String input = JOptionPane.showInputDialog("Enter " + "total numbers to be entered: "); totalNumbers = Integer.parseInt(input); for(intcount=0; count < totalNumbers; count++ ) { input = JOptionPane.showInputDialog("Enter " + "a number: "); //number = Double.parseDouble(input); sumNumbers = sumNumbers + Double.parseDouble(input); } JOptionPane.showMessageDialog(null, String.format("The sum of %d numbers is %.2f.", totalNumbers, sumNumbers)); System.exit(0); } }

  45. import java.util.Scanner; publicclass TotalSales { publicstaticvoid main(String[] args) { intsumNumbers = 0; inttotalNumbers = 0; intnumber; Scanner kb = new Scanner(System.in); System.out.println("Enter a positive number, " + "otherwise -1 for ending"); number = kb.nextInt(); while(number != -1) { totalNumbers++; sumNumbers += number; System.out.println("Enter a positive number, " + "otherwise -1 for ending"); number = kb.nextInt(); } System.out.printf("Sum of the %d numbers is %d.\n", totalNumbers, sumNumbers );

  46. Enter a positive number, otherwise -1 for ending 101 Enter a positive number, otherwise -1 for ending 102 Enter a positive number, otherwise -1 for ending 103 Enter a positive number, otherwise -1 for ending -1 Sum of the 3 numbers is 306.

  47. Nested Loops Like if statements, loops can be nested. If a loop is nested, the inner loop will execute all of its iterations for each time the outer loop executes once. for(int i = 0; i < 10; i++) for(int j = 0; j < 10; j++) loop statements; The loop statements in this example will execute 100 times. Example: Clock.java for(inti = 0; i < 10; i++) { for(int j = 0; j < 10; j++) loop statements; }

  48. i is 0 j is 0 j is 1 j is 2 j is 3 j is 4 i is 1 j is 0 j is 1 j is 2 j is 3 j is 4 i is 2 j is 0 j is 1 j is 2 j is 3 j is 4 finalintiLimit = 3; finalintjLimit = 5; for(inti = 0; i < iLimit; i++) { System.out.println("i is " + i); for(intj = 0; j < jLimit; j++) System.out.println(" j is " + j); }

  49. finalintiLimit = 3; finalintjLimit = 5; for(inti = 0; i < iLimit; i++) { System.out.println(""); for(intj = 0; j < jLimit; j++) System.out.print(j + " "); } System.out.println("\nThis is"); intx = 0, col = 0; for(introw = 0; row < iLimit; row++) { System.out.println(""); for(; col < (row+1)*jLimit; col++) { System.out.print(col + " "); x = col + 1; } x = col + 1; } 0 1 2 3 4 0 1 2 3 4 0 1 2 3 4 This is 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14

More Related