Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

MELJUN CORTES Java Repition Structures


Published on

MELJUN CORTES Java Repition Structures

  • Be the first to comment

  • Be the first to like this

MELJUN CORTES Java Repition Structures

  2. 2. Chapter 6 Objectives After you have read and studied this chapter, you should be able to • Implement repetition control in a program by using while statements. • Implement repetition control in a program by using do-while statements. • Implement a generic loop-and-a-half repetition control statement. • Implement repetition control in a program by using for statements. MELJUN CORTES,MBA,MPA,BSCS,ACS
  3. 3. Chapter 6 Objectives, cont. After you have read and studied this chapter, you should be able to • Nest a loop repetition statement inside another repetition statement. • Choose the appropriate repetition control statement for a given task. • Prompt the user for a yes/no reply by using the showConfirmDialog method from the JOptionPane class. • (Optional) Write simple recursive methods. MELJUN CORTES,MBA,MPA,BSCS,ACS
  4. 4. 6.1 The while Statement Repetition statements control a block of code to be executed for a fixed number of times or until a certain condition is met. Java has three repetition statements: • while • do-while • for MELJUN CORTES,MBA,MPA,BSCS,ACS
  5. 5. 6.1 The while Statement In Java, while statements follow a general format: while ( <boolean expression> ) <statement> For example: int sum = 0, number = 1; while (number <= 100){ sum = sum + number; number = number + 1; } MELJUN CORTES,MBA,MPA,BSCS,ACS
  6. 6. 6.1 The while Statement Repetition statements are also called loop statements, and the <statement> is known as the loop body. As long as the <boolean expression> is true, the loop body is executed. MELJUN CORTES,MBA,MPA,BSCS,ACS
  7. 7. Fig. 6.1 Correspondence of the example while statement to the general format. MELJUN CORTES,MBA,MPA,BSCS,ACS
  8. 8. Fig. 6.2 A diagram showing the control flow of a while statement. MELJUN CORTES,MBA,MPA,BSCS,ACS
  9. 9. 6.1 The while Statement In a count-controlled loop, the loop body is executed a fixed number of times. In a sentinel-controlled loop, the loop body is executed repeatedly until a designated value, called a sentinel, is encountered. MELJUN CORTES,MBA,MPA,BSCS,ACS
  10. 10. 6.2 Pitfalls inWriting Repetition Statements When writing repetition statements, it is important to ensure that the loop will eventually terminate. There are several different types of potential programming problems we should keep in mind as we develop our programs. MELJUN CORTES,MBA,MPA,BSCS,ACS
  11. 11. 6.2 Pitfalls inWriting Repetition Statements Infinite loop int product = 0; while (product < 5000) { product = product * 5; } Because product is initialized to 0, product will never be larger than 5000 (0 = 0 * 5), so the loop will never terminate. MELJUN CORTES,MBA,MPA,BSCS,ACS
  12. 12. 6.2 Pitfalls inWriting Repetition Statements Overflow error int count = 1; while (count != 10) { count = count + 2; } In this example, (the while statement of which is also an infinite loop), count will equal 9 and 11, but not 10. MELJUN CORTES,MBA,MPA,BSCS,ACS
  13. 13. 6.2 Pitfalls inWriting Repetition Statements An overflow error occurs when you attempt to assign a value larger than the maximum value the variable can hold. In Java, an overflow does not cause program termination. With types float and double, a value that represents infinity is assigned to the variable. With type int, the value “wraps around” and becomes a negative value. MELJUN CORTES,MBA,MPA,BSCS,ACS
  14. 14. 6.2 Pitfalls inWriting Repetition Statements Real numbers should not be used in testing or increment, because only an approximation of real numbers can be stored in a computer. The off-by-one error is another frequently-encountered pitfall. MELJUN CORTES,MBA,MPA,BSCS,ACS
  15. 15. 6.3 The do-while Statement The while statement is a pretest loop, because the test is done before the execution of the loop body. Therefore, the loop body may not be executed. The do-while statement is a posttest loop. With a posttest loop statement, the loop body is executed at least once. MELJUN CORTES,MBA,MPA,BSCS,ACS
  16. 16. 6.3 The do-while Statement The format of the do-while statement is: do <statement> while (<boolean expression>); The <statement> is executed until the <boolean expression> becomes false. MELJUN CORTES,MBA,MPA,BSCS,ACS
  17. 17. 6.3 The do-while Statement int sum = 0, number = 1; do{ sum += number; number++; } while (sum <=1000000); MELJUN CORTES,MBA,MPA,BSCS,ACS
  18. 18. Fig. 6.3 Correspondence of the example do- while statement to the general format. MELJUN CORTES,MBA,MPA,BSCS,ACS
  19. 19. Fig. 6.4 A diagram showing the control flow of the do-while statement. MELJUN CORTES,MBA,MPA,BSCS,ACS
  20. 20. 6.4 Loop-and-a-Half Repetition Control Loop-and-a-half repetition control can be used to test a loop’s terminating condition in the middle of the loop body. It is implemented by using reserved words while, if, and break. MELJUN CORTES,MBA,MPA,BSCS,ACS
  21. 21. 6.4 Loop-and-a-Half Repetition Control String name; while (true){ name = JOptionPane.showInputDialog(null, “Your name”); if (name.length() > 0) break; JOptionPane.showMessageDialog(null, “Invalid Entry.” + “You must enter at least one character.”); } MELJUN CORTES,MBA,MPA,BSCS,ACS
  22. 22. Fig. 6.5 A diagram showing the control flow of a loop-and-a-half statement. MELJUN CORTES,MBA,MPA,BSCS,ACS
  23. 23. 6.4 Loop-and-a-Half Repetition Control Be aware of two concerns when using the loop-and-a-half control: • The danger of an infinite loop. The boolean expression of the while statement is true, which will always evaluate to true. If we forget to include an if statement to break out of the loop, it will result in an infinite loop. MELJUN CORTES,MBA,MPA,BSCS,ACS
  24. 24. 6.4 Loop-and-a-Half Repetition Control • Multiple exit points. It is possible, although complex, to write a correct control loop with multiple exit points (breaks). It is good practice to enforce the one-entry one-exit control flow. MELJUN CORTES,MBA,MPA,BSCS,ACS
  25. 25. 6.5 Confirmation Dialog A confirmation dialog can be used to prompt the user to determine whether to continue a repetition or not. JOptionPane.showConfirmDialog(null, /*prompt*/ “Play Another Game?”, /*dialog title*/ “Confirmation”, /*button options*/ JOptionPane.YES_NO_OPTION); Executing the code above will result in Fig. 6.6. MELJUN CORTES,MBA,MPA,BSCS,ACS
  26. 26. Fig. 6.6 A confirmation dialog created by using the showConfirmDialog method of the JOptionPane class. MELJUN CORTES,MBA,MPA,BSCS,ACS
  27. 27. 6.5 Confirmation Dialog Used in a loop statement: boolean keepPlaying = true; int selection; while (keepPlaying){ //code to play one game comes here selection = JOptionPane.showConfirmDialog(null, “Play Another Game”, “Confirmation”, JOptionPane.YES_NO_OPTION); keepPlaying = (selection == JOptionPane.YES_OPTION); } MELJUN CORTES,MBA,MPA,BSCS,ACS
  28. 28. 6.6 The for Statement The format of the for statement is as follows: for (<initialization>; <boolean expression>; <increment>) <statement> int i, sum = 0; for (i = 1,i <=100, i++){ sum += i; //equivalent to sum = sum + 1; } MELJUN CORTES,MBA,MPA,BSCS,ACS
  29. 29. Fig. 6.7 Correspondence of the example for statement to the general format MELJUN CORTES,MBA,MPA,BSCS,ACS
  30. 30. Fig. 6.8 A diagram showing the control flow of the example for statement. MELJUN CORTES,MBA,MPA,BSCS,ACS
  31. 31. 6.6 The for Statement The variable i in the example statement is called a control variable. It keeps track of the number of repetitions. The <increment> can be by any amount, positive or negative. MELJUN CORTES,MBA,MPA,BSCS,ACS
  32. 32. 6.6 The for Statement /* Chapter 6 Sample Program: Dropping a Watermelon File: */ import javabook.*; import*; class Ch6DroppingWaterMelon { public static void main(String[] args){ double initialHeight, position, touchTime; MELJUN CORTES,MBA,MPA,BSCS,ACS
  33. 33. 6.6 The for Statement Scanner scanner = new Scanner(; scanner.useDelimiter( System.getProperty("line.separator")); System.out.print("Initial Height:"); initialHeight = scanner.nextDouble(); touchTime = Math.sqrt(initialHeight / 16.0); touchTime = Math.round(touchTime * 10000.0) / 10000.0; //convert to four decimal places System.out.println( "nn Time t Position at Time t n"); MELJUN CORTES,MBA,MPA,BSCS,ACS
  34. 34. 6.6 The for Statement for (int time = 0; time < touchTime; time++) { position = -16.0 * time*time + initialHeight; System.out.print(" " + time); System.out.println(" " + position); } //print the last second System.out.println(" " + touchTime + " 0.00"); System.out.println("nnn"); } } MELJUN CORTES,MBA,MPA,BSCS,ACS
  35. 35. 6.6 The for Statement An illustration of the program. MELJUN CORTES,MBA,MPA,BSCS,ACS
  36. 36. Fig. 6.9 The positions of a watermelon dropped from a height of 500 ft. MELJUN CORTES,MBA,MPA,BSCS,ACS
  37. 37. 6.7 Nested-for Statements Nested-for statements are for statements embedded within other for statements. int price; for (int width = 11; width <=20, width++){ for (int length = 5, length <=25, length+=5){ price = width * length * 19; //$19 per sq. ft. System.out.print (“ “+ price); } //finished one row; move on to next row System.out.println(“”); } MELJUN CORTES,MBA,MPA,BSCS,ACS
  38. 38. Fig. 6.10 The price table for carpets ranging in size from 11 × 5 to 20 × 25 ft. whose unit price is $19 per sq. ft. MELJUN CORTES,MBA,MPA,BSCS,ACS
  39. 39. 6.7 Nested-for Statements The outer for statement ranges from the first row (width = 11) to the last row (width = 20). For each repetition of the outer for, the inner for statement is executed, which ranges from the first column (length = 5) to the fifth (length = 25). MELJUN CORTES,MBA,MPA,BSCS,ACS
  40. 40. 6.8 Formatting Output To align values with varying numbers of digits, we must vary the number of spaces in front of the values. The idea behind formatted output is to allocate the same amount of space for the output values and align the values within the allocated space. MELJUN CORTES,MBA,MPA,BSCS,ACS
  41. 41. Fig. 6.11 The price table for carpets with $15 per sq. ft. and width ranging from 5-14 ft. MELJUN CORTES,MBA,MPA,BSCS,ACS
  42. 42. 6.8 Formatting Output We call the space occupied by an output value the field. The number of characters allocated to a field is the field width. MELJUN CORTES,MBA,MPA,BSCS,ACS
  43. 43. Fig. 6.12 How to place a varying number of spaces to align the output values. Hyphen is used here to indicate the blank space. MELJUN CORTES,MBA,MPA,BSCS,ACS
  44. 44. 6.8 Formatting Output We use the Formatter class to format the output. First we create an instance of the class Formatter formatter = new Formatter(System.out); Then we call its format method int num = 467; formatter.format("%6d", num); This will output the value with the field width of 6. MELJUN CORTES,MBA,MPA,BSCS,ACS
  45. 45. 6.8 Formatting Output The general syntax is format(<control string>, <expr1>, <expr2>, . . . ) int num1 = 34, num2 = 9; int num3 = num1 + num2; formatter.format("%3d + %3d = %5d", num1, num2, num3); MELJUN CORTES,MBA,MPA,BSCS,ACS
  46. 46. 6.8 Formatting Output /* Chapter 6 Sample Program: Sample formatting statements File: */ //import javabook.*; import*; class Ch6CarpetPriceTableWithFormat { public static void main (String[] args){ int price; //print out the colum labels System.out.print(" "); MELJUN CORTES,MBA,MPA,BSCS,ACS
  47. 47. 6.8 Formatting Output for (int colLabel = 5; colLabel <=25; colLabel += 5) { System.out.format("%8d", colLabel); } System.out.println(""); System.out.println(""); //print out rows of prices for (int width = 5; width <= 14; width++) { System.out.format("%3d", width); for (int length = 5; length <= 25; length += 5) { price = width * length * 15; System.out.format("%8d", price); } //finished one row; now move on to the next row System.out.println(""); } System.out.println(""); System.out.println(""); } } MELJUN CORTES,MBA,MPA,BSCS,ACS
  48. 48. Fig. 6.13 Carpet price table of Fig. 6.11 with proper alignment. MELJUN CORTES,MBA,MPA,BSCS,ACS
  49. 49. 6.9 Loan Tables The goal of this exercise is to design a program that generates a loan table. The table will compare different monthly payments for a set loan amount, with varying loan periods in each column and different interest rates in each row. MELJUN CORTES,MBA,MPA,BSCS,ACS
  50. 50. 6.9 Loan Tables The start method can be expressed as tell the user what the program does; prompt the user “Do you want to generate a loan table?”; while (the user says YES){ input the loan amount; generate the loan table; prompt the user “Do you want another loan table?”; } MELJUN CORTES,MBA,MPA,BSCS,ACS
  51. 51. 6.9 Loan Tables The start method was expressed in pseudocode. Pseudocode is an informal language used to express an algorithm. It is useful in clarifying the purpose or function of the program without being tied down to the syntactic rules of a programming language. MELJUN CORTES,MBA,MPA,BSCS,ACS
  52. 52. 6.9 Loan Tables public void start () { int response; describeProgram(); response = prompt(“Generate a loan table?”); while (response == JOptionPane.YES_OPTION){ loanAmount = getLoanAmount(); //get input generateLoanTable(loanAmount);//generate table response = prompt(“Generate another loan table?”); } } MELJUN CORTES,MBA,MPA,BSCS,ACS
  53. 53. 6.9 Loan Tables private int prompt(String question){ int reply; reply = JOptionPane.showConfirmDialog(null, question, “Confirmation”, JOptionPane.YES_NO_OPTION); return reply; } MELJUN CORTES,MBA,MPA,BSCS,ACS
  54. 54. 6.9 Loan Tables Other methods in the program: describeProgram: tells the user what the program does if the user requests it. getLoanAmount: gets the loan amount from the user. generateLoanTable: generates the loan table. MELJUN CORTES,MBA,MPA,BSCS,ACS
  55. 55. 6.9 Loan Tables To compute the monthly loan payment, reuse the Loan class defined in Chapter 4. MELJUN CORTES,MBA,MPA,BSCS,ACS
  56. 56. 6.10 Random Number Generation The method random is called a pseudorandom number generator and returns a number of type double that is greater than or equal to 0.0 but less than 1.0. The generated number is called a pseudorandom number because it is not truly random. MELJUN CORTES,MBA,MPA,BSCS,ACS
  57. 57. 6.10 Random Number Generation If we want to generate an integer, and the number returned from the random method ranges from 0.0 up to (but not including) 1.0, we must perform a conversion so the number will fall within the desired range. Use the formula: Y = {X × (max – min + 1)} + min where X is the number returned by random. MELJUN CORTES,MBA,MPA,BSCS,ACS
  58. 58. 6.10 Random Number Generation The formula is thus expressed in Java: //assume correct values are assigned to //‘max’ and ‘min’ int randomNumber = (int) (Math.floor(Math.random * max-min+1)) + min); MELJUN CORTES,MBA,MPA,BSCS,ACS
  59. 59. 6.10 Random Number Generation The following program generates N random numbers between 1 and 4 to simulate the suit of a drawn card. It keeps one counter for each suit, and increments the matching counter after a random number is generated. At the end of the generation, it prints the ratio count/N. MELJUN CORTES,MBA,MPA,BSCS,ACS
  60. 60. 6.10 Random Number Generation /* Chapter 6 Sample Program: Test the random number generator File: */ import javax.swing.*; import java.util.*; class Ch6TestRandomGenerator { private static final int CLUB = 1; private static final int SPADE = 2; private static final int HEART = 3; private static final int DIAMOND = 4; public static void main( String[] args ) { Ch6TestRandomGenerator tester = new Ch6TestRandomGenerator(); tester.start(); } MELJUN CORTES,MBA,MPA,BSCS,ACS
  61. 61. 6.10 Random Number Generation public void start( ) { long N; while (keepTesting()) { N = getSize(); generate(N); } } private long getSize( ) { String inputStr; long size; while (true) { inputStr = JOptionPane.showInputDialog(null, "Enter size:"); size = Long.parseLong(inputStr); if (size > 0) break; //input okay so exit JOptionPane.showMessageDialog(null, "Input must be positive"); } return size; } MELJUN CORTES,MBA,MPA,BSCS,ACS
  62. 62. 6.10 Random Number Generation private void generate(long size) { Date startTime, endTime; int suit; long clubCnt, spadeCnt, heartCnt, diamondCnt; clubCnt = spadeCnt = heartCnt = diamondCnt = 0; startTime = new Date(); for (int i = 0; i < size; i++) { suit = getRandom(CLUB, DIAMOND); switch (suit) { case CLUB: clubCnt++; break; case SPADE: spadeCnt++; break; case HEART: heartCnt++; break; MELJUN CORTES,MBA,MPA,BSCS,ACS
  63. 63. 6.10 Random Number Generation case DIAMOND: diamondCnt++; break; default: //default case should never happen JOptionPane.showMessageDialog(null, "Internal Error"); System.exit(0); //terminate the program } } endTime = new Date(); System.out.println("N is " + size + "n"); System.out.println("Club: " + clubCnt + " " + (double)clubCnt/size); System.out.println("Spade: " + spadeCnt + " " + (double)spadeCnt/size); System.out.println("Heart: " + heartCnt + " " + (double)heartCnt/size); System.out.println("Diamond: " + diamondCnt + " " + (double)diamondCnt/size); MELJUN CORTES,MBA,MPA,BSCS,ACS
  64. 64. 6.10 Random Number Generation double elapsedTimeInSec = (double) (endTime.getTime() - startTime.getTime())/1000.0; System.out.println("Elapsed time (sec): " + elapsedTimeInSec ); System.out.println("n"); } private int getRandom(int min, int max) { int randomNumber = (int) (Math.floor(Math.random() * (max-min+1)) + min); return randomNumber; } private boolean keepTesting( ) { boolean result; int response = JOptionPane.showConfirmDialog(null, /*prompt*/ "Perform Test?", /*dialog title*/ "Random Number Generator", /*button options*/ JOptionPane.YES_NO_OPTION); MELJUN CORTES,MBA,MPA,BSCS,ACS
  65. 65. 6.10 Random Number Generation if (response == JOptionPane.YES_OPTION) { result = true; } else { result = false; } return result; } } MELJUN CORTES,MBA,MPA,BSCS,ACS