Tài liệu Bài giảng Chapter 6: Repetition Statements: Chapter 6Repetition Statements©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.Chapter 6 ObjectivesAfter you have read and studied this chapter, you should be able toImplement 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.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.Chapter 6 Objectives, cont.After you have read and studied this chapter, you should be able toNest 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.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display...
68 trang |
Chia sẻ: honghanh66 | Lượt xem: 1293 | Lượt tải: 0
Bạn đang xem trước 20 trang mẫu tài liệu Bài giảng Chapter 6: Repetition Statements, để tải tài liệu gốc về máy bạn click vào nút DOWNLOAD ở trên
Chapter 6Repetition Statements©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.Chapter 6 ObjectivesAfter you have read and studied this chapter, you should be able toImplement 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.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.Chapter 6 Objectives, cont.After you have read and studied this chapter, you should be able toNest 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.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.6.1 The while StatementRepetition 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:whiledo-whilefor©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.6.1 The while StatementIn Java, while statements follow a general format: while ( ) For example:int sum = 0, number = 1;while (number is known as the loop body. As long as the is true, the loop body is executed.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.Fig. 6.1Correspondence of the example while statement to the general format.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.Fig. 6.2A diagram showing the control flow of a while statement.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.6.1 The while StatementIn 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.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.6.2 Pitfalls in Writing Repetition StatementsWhen 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.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.6.2 Pitfalls in Writing Repetition StatementsInfinite loopint product = 0; while (product while ();The is executed until the becomes false.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.6.3 The do-while Statementint sum = 0, number = 1;do{ sum += number; number++;} while (sum 0) break; JOptionPane.showMessageDialog(null, “Invalid Entry.” + “You must enter at least one character.”);}©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.Fig. 6.5A diagram showing the control flow of a loop-and-a-half statement.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.6.4 Loop-and-a-Half Repetition ControlBe 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.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.6.4 Loop-and-a-Half Repetition ControlMultiple 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. ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.6.5 Confirmation DialogA 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.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.Fig. 6.6A confirmation dialog created by using the showConfirmDialog method of the JOptionPane class.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.6.5 Confirmation DialogUsed 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);}©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.6.6 The for StatementThe format of the for statement is as follows:for (; ; ) int i, sum = 0;for (i = 1,i can be by any amount, positive or negative.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.6.6 The for Statement/* Chapter 6 Sample Program: Dropping a Watermelon File: Ch6DroppingWaterMelon.java*/import javabook.*;import java.io.*;class Ch6DroppingWaterMelon { public static void main( String[] args ) throws IOException { double initialHeight, position, touchTime; ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.6.6 The for Statement BufferedReader bufReader = new BufferedReader( new InputStreamReader( System.in )); System.out.print("Initial Height:"); InitialHeight=Double.parseDouble(bufReader.readLine( )); touchTime = Math.sqrt(initialHeight /16.0); touchTime = Math.round(touchTime * 10000.0) / 10000.0; //convert to four decimal places System.out.println("\n\n Time t Position at Time t \n"); ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.6.6 The for Statementfor (int time = 0; time 0) break; //input okay so exit JOptionPane.showMessageDialog(null, "Input must be positive"); } return size;} ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.6.10 Random Number Generationprivate 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; ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.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); ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.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); ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.6.10 Random Number Generation if (response == JOptionPane.YES_OPTION) { result = true; } else { result = false; } return result; }}©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
Các file đính kèm theo tài liệu này:
- chapter_6_8121.ppt