1 / 77

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.

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

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

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

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

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

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

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

  11. The while loop Flowchart boolean expression? false true statement(s)

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

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

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

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

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

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

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

  19. The do-while Loop Flowchart statement(s) true boolean expression? false

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

  21. The for Loop Flowchart false boolean expression? true statement(s) update initialization

  22. 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! intj = 0; do { System.out.println(j); j++; }while (j < 5); int k = 0; while (k < 5) { System.out.println(k); k++; } 0 1 2 3 4 0 1 2 3 4 0 1 2 3 4

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

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

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

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

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

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

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

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

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

  32. Logic for Calculating a Running Total

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

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

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

  36. Enter a positive number, otherwise -1 for ending -1 Sum of the 0 numbers is 0.00. Enter a positive number, otherwise -1 for ending 101.01 Enter a positive number, otherwise -1 for ending -1 Sum of the 1 numbers is 101.01. Enter a positive number, otherwise -1 for ending 202.02 Enter a positive number, otherwise -1 for ending 303.0399 Enter a positive number, otherwise -1 for ending -1 Sum of the 2 numbers is 505.06.

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

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

  39. Nested Loops 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; • for(inti = 0; i < 10; i++) • { • for(int j = 0; j < 10; j++) • { • loop statements; • }//end inner for_loop • }//end outer for_loop

  40. The break Statement The break statement can be used to abnormally terminate a loop. The use of the break statement in loops bypasses the normal mechanisms and makes the code hard to read and maintain. It is considered bad form to use the break statement in this manner.

  41. charswitchExpr; switchExpr = 'a'; switch (switchExpr) { case'A’: case'a’: System.out.println("This is one!"); break; case'B’: case'b’: System.out.println("This is two!"); break; default: System.out.println("This is out!"); }

  42. import javax.swing.JOptionPane; publicclass ReadWriteFile { publicstaticvoid main(String[] args) { charswitchExpr; //switchExpr = 'a'; String str = JOptionPane.showInputDialog("Enter a character: "); switchExpr = str.charAt(0); switch (switchExpr) { case'A': case'a': System.out.println("This is one!"); break; case'B': case'b': System.out.println("This is two!"); break; default: System.out.println("This is out!"); } System.exit(0); } }

  43. String str = JOptionPane.showInputDialog("Enter " + "a word:"); str = str.toUpperCase(); switch (str) { case"PETER": System.out.printf("The name is %s.\n", str); break; case"PAUL": System.out.printf("The name is %s.\n", str); break; default: System.out.println("No Peter and Paul."); }

  44. import javax.swing.JOptionPane; publicclass ReadWriteFile { publicstaticvoid main(String[] args) { String str = JOptionPane.showInputDialog("Enter " + "a word:"); //str = str.toUpperCase(); if (str.equalsIgnoreCase("PETER")) System.out.printf("The name is %s.\n", str); elseif(str.equalsIgnoreCase("PAUL")) System.out.printf("The name is %s.\n", str); else System.out.println("No Peter and Paul."); System.exit(0); } }

  45. if (str.equals("PETER")) switchExpr = str.charAt(0); elseif ("Paul".equalsIgnoreCase(str)) switchExpr = str.charAt(1); elseswitchExpr = str.charAt(0); switch (switchExpr) { case'P’: case'p’: System.out.println("This is one, P!"); break; case'a’: case'A’: System.out.println("This is two, Paul!"); break; default: System.out.println("This is out Not p from" + " Peter or not a from Paul!"); }

  46. import javax.swing.JOptionPane; publicclass ReadWriteFile { publicstaticvoid main(String[] args) { String str = JOptionPane.showInputDialog("Enter " + "a word:"); System.out.println("The str " + str + “ compareTo(\"PETER\") is " + str.compareTo("PETER") ); System.exit(0); } } The str PETER compareTo("PETER") is 0 The str PETERABC compareTo("PETER") is 3 The strPETErcompareTo("PETER") is 32 //ASCII code for r is 114 and R is 82 and the difference is 114-82 = 32

  47. The continue Statement The continue statement will cause the currently executing iteration of a loop to terminate and the next iteration will begin. The continue statement will cause the evaluation of the condition in while and for loops. Like the break statement, the continue statement should be avoided because it makes the code hard to read and debug.

  48. Import java.util.JOptionPane; publicclass TotalSales { publicstaticvoid main(String[] args) { double sumNumbers = 0; //int totalNumbers = 5; double number; String task = "Enter total numbers to be entered: "; String title = "Determine Sum of Numbers"; String input = JOptionPane.showInputDialog(null, task, title, JOptionPane.QUESTION_MESSAGE); //create a name constant with the modifier final. final int totalNumbers = Integer.parseInt(input); for(int count=0; count < totalNumbers; count++ ) { input = JOptionPane.showInputDialog(null, "Enter a number: ", title, JOptionPane.QUESTION_MESSAGE); //number = Double.parseDouble(input); sumNumbers = sumNumbers + Double.parseDouble(input); int yesNoCancel = JOptionPane.showConfirmDialog(null, "Continue to enter a number?", title + "Selection One!", JOptionPane.YES_NO_CANCEL_OPTION); if (yesNoCancel == JOptionPane.NO_OPTION) break; else if (yesNoCancel == JOptionPane.CANCEL_OPTION) { int yesNoContinue = JOptionPane.showConfirmDialog(null, "Do you continue to enter a number?", title + "Selection One!", JOptionPane.YES_NO_OPTION); if (yesNoContinue == JOptionPane.YES_OPTION) continue; else break; } } //end for JOptionPane.showMessageDialog(null, String.format("The sum of %d numbers is %.2f.", totalNumbers, sumNumbers), title, JOptionPane.INFORMATION_MESSAGE); System.exit(0); } }

  49. Deciding Which Loops to Use The while loop: Pretest loop Use it where you do not want the statements to execute if the condition is false in the beginning. The do-while loop: Post-test loop Use it where you want the statements to execute at least one time. The for loop: Pretest loop Use it where there is some type of counting variable that can be evaluated.

More Related