SlideShare a Scribd company logo
Chapter 6 Repetition Statements
Objectives After you have read and studied this chapter, you should be able to  Implement repetition control in a program using  while  statements. Implement repetition control in a program using  do-while  statements. Implement a generic loop-and-a-half repetition control statement Implement repetition control in a program using  for  statements. 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 using the  showConfirmDialog  method of  JOptionPane . (Optional) Write simple recursive methods
Definition Repetition statements control a block of code to be executed for a fixed number of times or until a certain condition is met. Count-controlled repetitions  terminate the execution of the block after it is executed for a fixed number of times. Sentinel-controlled repetitions  terminate the execution of the block after one of the designated values called a  sentinel  is encountered. Repetition statements are called  loop statements  also.
The  while  Statement int  sum = 0, number = 1; while   (  number <= 100  ) { sum  =  sum + number; number = number + 1; } These statements are executed as long as number is less than or equal to 100.
Syntax for the  while  Statement while   (  <boolean expression>  )   <statement> while   (   number <= 100  ) { sum  =  sum + number; number = number + 1; } Statement (loop body) Boolean Expression
Control Flow of  while int sum = 0, number = 1 number <= 100 ? false sum = sum + number; number = number + 1; true
More Examples Keeps adding the numbers 1, 2, 3, … until the sum becomes larger than 1,000,000. Computes the product of the first 20 odd integers. int  sum = 0, number = 1; while   (  sum <= 1000000  ) { sum  =  sum + number; number = number + 1; } 1 int  product =  1, number = 1,   count  = 20, lastNumber; lastNumber = 2 * count - 1; while   ( number <= lastNumber ) { product = product * number; number  = number + 2; } 2
Finding GCD
Example: Testing Input Data String inputStr; int   age; inputStr = JOptionPane.showInputDialog ( null , &quot;Your Age (between 0 and 130):&quot; ) ; age  = Integer.parseInt ( inputStr ) ; while   ( age < 0 || age > 130 ) { JOptionPane.showMessageDialog ( null , &quot;An invalid age was entered. Please try again.&quot; ) ; inputStr = JOptionPane.showInputDialog ( null , &quot;Your Age (between 0 and 130):&quot; ) ; age = Integer.parseInt ( inputStr ) ;  } Priming Read
Useful Shorthand Operators sum = sum + number; sum += number; is equivalent to Meaning Usage Operator a = a % b; a %= b; %= a = a / b; a /= b; /= a = a * b; a *= b; *= a = a – b; a -= b; -= a = a + b; a += b; +=
Watch Out for Pitfalls Watch out for the off-by-one error (OBOE). Make sure the loop body contains a statement that will eventually cause the loop to terminate. Make sure the loop repeats exactly the correct number of times.  If you want to execute the loop body N times, then initialize the counter to  0  and use the test condition counter  < N  or initialize the counter to  1  and use the test condition counter  <= N .
Loop Pitfall - 1 Infinite Loops   Both loops will not terminate because the boolean expressions will never become false. int  count = 1; while   (  count != 10  ) { count = count + 2; } 2 int  product = 0; while   (  product < 500000  ) { product = product * 5; } 1
Overflow An infinite loop often results in an overflow error. 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.
Loop Pitfall - 2 Using Real Numbers   Loop 2 terminates, but Loop 1 does not because only an approximation of a real number can be stored in a computer memory. float  count = 0.0f; while   (  count != 1.0f  ) { count = count + 0.33333333f; }   //eight 3s 2 float  count = 0.0f; while   (  count != 1.0f  ) { count = count + 0.3333333f; } //seven 3s 1
Loop Pitfall – 2a int  result = 0;  double  cnt = 1.0; while   ( cnt <= 10.0 ){ cnt += 1.0; result++; } System.out.println ( result ) ; 1 int  result = 0;  double  cnt = 0.0; while   ( cnt <= 1.0 ){ cnt += 0.1; result++; } System.out.println ( result ) ; 2 Using Real Numbers   Loop 1 prints out 10, as expected, but Loop 2 prints out 11. The value 0.1 cannot be stored precisely in computer memory. 10 11
Loop Pitfall - 3 Goal: Execute the loop body 10 times. count = 1; while   (  count < 10  ){ . . . count++; } 1 count = 0; while   (  count <= 10  ){ . . . count++; } 3 count = 1; while   (  count <= 10  ){ . . . count++; } 2 count = 0; while   (  count < 10  ){ . . . count++; } 4 1 3 and exhibit  off-by-one  error.
The  do - while  Statement int sum = 0, number = 1; do { sum += number; number++; } while ( sum <= 1000000 ); These statements are executed as long as sum is less than or equal to 1,000,000.
Syntax for the  do - while  Statement do <statement> while   (  <boolean expression>  )  ; do   { sum += number; number++; }   while   (   sum <= 1000000  ) ; Statement (loop body) Boolean Expression
Control Flow of  do - while int sum = 0, number = 1 sum += number; number++; sum <= 1000000 ? true false
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 .
Example: Loop-and-a-Half Control String name; while   ( true ){ name = JOptionPane.showInputDialog ( null ,  &quot;Your name&quot; ) ; if   ( name.length ()  > 0 )   break ; JOptionPane.showMessageDialog ( null ,  &quot;Invalid Entry.&quot;  +    &quot;You must enter at least one character.&quot; ) ; }
Pitfalls for Loop-and-a-Half 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. Multiple exit points.  It is possible, although complex, to write a correct control loop with multiple exit points  (break s). It is good practice to enforce the  one-entry one-exit control  flow.
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*/     &quot;Play Another Game?&quot; , /*dialog title*/   &quot;Confirmation&quot; , /*button options*/  JOptionPane.YES_NO_OPTION ) ;
Example: Confirmation Dialog boolean  keepPlaying =  true ; int    selection; while   ( keepPlaying ){ //code to play one game comes here // . . . selection = JOptionPane.showConfirmDialog ( null ,     &quot;Play Another Game?&quot; ,   &quot;Confirmation&quot; ,   JOptionPane.YES_NO_OPTION ) ; keepPlaying =  ( selection == JOptionPane.YES_OPTION ) ; }
The  for  Statement int  i, sum = 0, number; for   ( i = 0; i < 20; i++ )   { number = scanner.nextInt ( ) ; sum += number; } These statements are executed for  20  times  (  i = 0, 1, 2, … , 19 ).
Syntax for the  for  Statement for   (  <initialization>; <boolean expression>; <increment>  ) <statement> for (  i = 0  ;  i < 20  ;  i++  ) { number = scanner.nextInt(); sum += number; } Initialization Boolean Expression Increment Statement (loop body)
Control Flow of  for i = 0; false number  = . . . ; sum  += number; true i ++; i < 20 ?
More  for  Loop Examples i = 0, 5, 10, … , 95 j = 2, 4, 8, 16, 32 k = 100, 99, 98, 97, ..., 1 for (int i = 0; i < 100; i += 5) 1 for (int j = 2; j < 40; j *= 2) 2 for (int k = 100; k > 0; k--) ) 3
The Nested-for Statement Nesting a  for  statement inside another for statement is commonly used technique in programming. Let’s generate the following table using nested-for statement.
Generating the Table 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 ( “” ) ; } INNER OUTER
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 . The diagram shows the field width of 6. From Java 5.0, we can use the  Formatter  class.  System.out  ( PrintStream ) also includes the format method.
The Formatter Class 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(&quot;%6d&quot;, num); This will output the value with the field width of 6.
The format Method of Formatter The general syntax is format(<control string>,  <expr1>, <expr2>, . . . ) Example: int num1 = 34, num2 = 9;   int num3 = num1 + num2;   formatter.format(&quot;%3d + %3d = %5d&quot;, num1, num2, num3);
The format Method of PrintStream Instead of using the Formatter class directly, we can achieve the same result by using the format method of PrintStream (System.out) Formatter formatter = new Formatter(System.out); formatter.format(&quot;%6d&quot;, 498); is equivalent to System.out.format( &quot;%6d&quot;, 498 );
Control Strings Integers % <field width> d Real Numbers % <field width> . <decimal places> f Strings % s For other data types and more formatting options, please consult the Java API for the Formatter class.
Estimating the Execution Time In many situations, we would like to know how long it took to execute a piece of code. For example, Execution time of a loop statement that finds the greatest common divisor of two very large numbers, or Execution time of a loop statement to display all prime numbers between 1 and 100 million Execution time can be measured easily by using the Date class.
Using the Date Class Here's one way to measure the execution time Date startTime = new Date(); //code you want to measure the execution time Date endTime = new Date(); long elapsedTimeInMilliSec = endTime.getTime() – startTime.getTime();
Problem Statement Problem statement: Write an application that will play Hi-Lo games with the user. The objective of the game is for the user to guess the computer-generated secret number in the least number of tries. The secret number is an integer between 1 and 100, inclusive. When the user makes a guess, the program replies with HI or LO depending on whether the guess is higher or lower than the secret number. The maximum number of tries allowed for each game is six. The user can play as many games as she wants.
Overall Plan Tasks: do   { Task 1: generate a secret number ; Task 2: play one game ; }   while   (   the user wants to play   ) ;
Required Classes main class standard classes Ch6HiLo JOptionPane Math
Development Steps We will develop this program in four steps: Start with a skeleton Ch6HiLo class. Add code to the Ch6HiLo class to play a game using a dummy secret number. Add code to the Ch6HiLo class to generate a random number. Finalize the code by tying up loose ends.
Step 1 Design The topmost control logic of HiLo 1. describe the game rules ; 2. prompt the user to play a game or not ; while   (   answer is yes   ) { 3. generate the secret number ; 4. play one game ; 5. prompt the user to play another game or  not ; }
Step 1 Code Directory:   Chapter6/Step1 Source Files:  Ch6HiLo.java Program source file is too big to list here. From now on, we ask you to view the source files using your Java IDE.
Step 1 Test In the testing phase, we run the program and verify confirm that the topmost control loop terminates correctly under different conditions. Play the game zero times one time one or more times
Step 2 Design Implement the playGame method that plays one game of HiLo.  Use a dummy secret number By using a fix number such as 45 as a dummy secret number, we will be able to test the correctness of the playGame method
The Logic of playGame int guessCount = 0; do   { get next guess ; guessCount++; if   ( guess < secretNumber ) { print the hint LO ; }   else if   ( guess > secretNumber ) { print the hint HI ; } }  while  ( guessCount < number of guesses allowed   && guess != secretNumber  ) ; if   ( guess  == secretNumber ) { print the winning message ;  }   else   { print the losing message ; }
Step 2 Code Directory:   Chapter6/Step2 Source Files:  Ch6HiLo.java
Step 2 Test We compile and run the program numerous times To test getNextGuess, enter a number less than 1 a number greater than 100 a number between 2 and 99 the number 1 and the number 100 To test playGame, enter a guess less than 45 a guess greater than 45 45 six wrong guesses
Step 3 Design We complete the generateSecretNumber method. We want to generate a number between 1 and 100 inclusively. private   void  generateSecretNumber ( ) { double  X = Math.random () ; secretNumber =  ( int )  Math.floor (  X * 100  )  + 1; System.out.println ( &quot;Secret Number: &quot;   + secretNumber ) ;  // TEMP return  secretNumber; }
Step 3 Code Directory:   Chapter6/Step3 Source Files:  Ch6HiLo.java
Step 3 Test We use a separate test driver to generate 1000 secret numbers. We run the program numerous times with different input values and check the results. Try both valid and invalid input values and confirm the response is appropriate
Step 4: Finalize Program Completion Finish the describeRules method Remove all temporary statements Possible Extensions Allow the user to set her desired min and max for secret numbers Allow the user to set the number of guesses allowed Keep the score—the number of guesses made —while playing games and display the average score when the user quits the program

More Related Content

What's hot (20)

PDF
Chap 5 c++
Venkateswarlu Vuggam
 
PPTX
12. Exception Handling
Intro C# Book
 
DOCX
Python unit 3 and Unit 4
Anandh Arumugakan
 
PPTX
Python Programming Essentials - M16 - Control Flow Statements and Loops
P3 InfoTech Solutions Pvt. Ltd.
 
PPT
C++ programming
viancagerone
 
PPTX
Working of while loop
Neeru Mittal
 
PPT
Chap 5 c++
Venkateswarlu Vuggam
 
PPT
FP 201 Unit 2 - Part 3
rohassanie
 
PPTX
Operators and Control Statements in Python
RajeswariA8
 
PPTX
03. Operators Expressions and statements
Intro C# Book
 
PPTX
Python
Sameeksha Verma
 
PPT
FP 201 Unit 3
rohassanie
 
PPTX
130707833146508191
Tanzeel Ahmad
 
PPT
06 Loops
maznabili
 
PPT
FP 201 - Unit 3 Part 2
rohassanie
 
PPTX
GE8151 Problem Solving and Python Programming
Muthu Vinayagam
 
PDF
Functional Programming in C#
Giorgio Zoppi
 
PDF
Nesting of for loops using C++
prashant_sainii
 
PDF
Introduction to python
Marian Marinov
 
PPTX
Unit2 control statements
deepak kumbhar
 
12. Exception Handling
Intro C# Book
 
Python unit 3 and Unit 4
Anandh Arumugakan
 
Python Programming Essentials - M16 - Control Flow Statements and Loops
P3 InfoTech Solutions Pvt. Ltd.
 
C++ programming
viancagerone
 
Working of while loop
Neeru Mittal
 
FP 201 Unit 2 - Part 3
rohassanie
 
Operators and Control Statements in Python
RajeswariA8
 
03. Operators Expressions and statements
Intro C# Book
 
FP 201 Unit 3
rohassanie
 
130707833146508191
Tanzeel Ahmad
 
06 Loops
maznabili
 
FP 201 - Unit 3 Part 2
rohassanie
 
GE8151 Problem Solving and Python Programming
Muthu Vinayagam
 
Functional Programming in C#
Giorgio Zoppi
 
Nesting of for loops using C++
prashant_sainii
 
Introduction to python
Marian Marinov
 
Unit2 control statements
deepak kumbhar
 

Viewers also liked (8)

PPT
Java căn bản - Chapter4
Vince Vo
 
PDF
Rama Ch11
Vince Vo
 
PDF
Rama Ch14
Vince Vo
 
PDF
Rama Ch12
Vince Vo
 
PPT
Java căn bản - Chapter2
Vince Vo
 
PPT
Java căn bản - Chapter7
Vince Vo
 
PDF
Rama Ch7
Vince Vo
 
PPT
Java căn bản - Chapter12
Vince Vo
 
Java căn bản - Chapter4
Vince Vo
 
Rama Ch11
Vince Vo
 
Rama Ch14
Vince Vo
 
Rama Ch12
Vince Vo
 
Java căn bản - Chapter2
Vince Vo
 
Java căn bản - Chapter7
Vince Vo
 
Rama Ch7
Vince Vo
 
Java căn bản - Chapter12
Vince Vo
 
Ad

Similar to Java căn bản - Chapter6 (20)

PPT
Ch5(loops)
Uğurcan Uzer
 
PPTX
Chapter 5 Loops by z al saeddddddddddddddddddddddddddddddddddd
zainaimadsaed
 
PPT
M C6java6
mbruggen
 
PPT
9 cm604.12
myrajendra
 
PPTX
Java Chapter 05 - Conditions & Loops: part 5
DanWooster1
 
DOCX
9 11 25 14 44 6 41 15 57 9 39 16 41 2 58 8 43 12 4.docx
ransayo
 
PPT
Chap05
Terry Yoast
 
PDF
DSA 103 Object Oriented Programming :: Week 3
Ferdin Joe John Joseph PhD
 
PPTX
Introduction to Java Programming - Lecture 11.pptx
AbdulKhaleqHerawi1
 
PPT
Java Programming: Loops
Karwan Mustafa Kareem
 
PPT
Comp102 lec 6
Fraz Bakhsh
 
PPT
Eo gaddis java_chapter_05_5e
Gina Bullock
 
PPT
Eo gaddis java_chapter_05_5e
Gina Bullock
 
PPTX
for loop in java
Majid Ali
 
PPT
9781439035665 ppt ch05
Terry Yoast
 
PPT
9 cm604.12
myrajendra
 
PPT
9781111530532 ppt ch05
Terry Yoast
 
PPT
9781111530532 ppt ch05
Terry Yoast
 
PPTX
Lesson 5
Fernando Loizides
 
PPT
04slidemicroemulsions microemulsions microemulsions microemulsions microemuls...
AhmadHashlamon
 
Ch5(loops)
Uğurcan Uzer
 
Chapter 5 Loops by z al saeddddddddddddddddddddddddddddddddddd
zainaimadsaed
 
M C6java6
mbruggen
 
9 cm604.12
myrajendra
 
Java Chapter 05 - Conditions & Loops: part 5
DanWooster1
 
9 11 25 14 44 6 41 15 57 9 39 16 41 2 58 8 43 12 4.docx
ransayo
 
Chap05
Terry Yoast
 
DSA 103 Object Oriented Programming :: Week 3
Ferdin Joe John Joseph PhD
 
Introduction to Java Programming - Lecture 11.pptx
AbdulKhaleqHerawi1
 
Java Programming: Loops
Karwan Mustafa Kareem
 
Comp102 lec 6
Fraz Bakhsh
 
Eo gaddis java_chapter_05_5e
Gina Bullock
 
Eo gaddis java_chapter_05_5e
Gina Bullock
 
for loop in java
Majid Ali
 
9781439035665 ppt ch05
Terry Yoast
 
9 cm604.12
myrajendra
 
9781111530532 ppt ch05
Terry Yoast
 
9781111530532 ppt ch05
Terry Yoast
 
04slidemicroemulsions microemulsions microemulsions microemulsions microemuls...
AhmadHashlamon
 
Ad

More from Vince Vo (19)

PPT
Java căn bản - Chapter13
Vince Vo
 
PPT
Java căn bản - Chapter10
Vince Vo
 
PPT
Java căn bản - Chapter9
Vince Vo
 
PPT
Java căn bản - Chapter8
Vince Vo
 
PPT
Java căn bản - Chapter5
Vince Vo
 
PPT
Java căn bản - Chapter3
Vince Vo
 
PPT
Java căn bản- Chapter1
Vince Vo
 
DOC
Hướng dẫn cài đặt Java
Vince Vo
 
PDF
Rama Ch13
Vince Vo
 
PDF
Rama Ch12
Vince Vo
 
PDF
Rama Ch10
Vince Vo
 
PDF
Rama Ch8
Vince Vo
 
PDF
Rama Ch9
Vince Vo
 
PDF
Rama Ch6
Vince Vo
 
PDF
Rama Ch5
Vince Vo
 
PDF
Rama Ch4
Vince Vo
 
PDF
Rama Ch3
Vince Vo
 
PDF
Rama Ch2
Vince Vo
 
PDF
Rama Ch1
Vince Vo
 
Java căn bản - Chapter13
Vince Vo
 
Java căn bản - Chapter10
Vince Vo
 
Java căn bản - Chapter9
Vince Vo
 
Java căn bản - Chapter8
Vince Vo
 
Java căn bản - Chapter5
Vince Vo
 
Java căn bản - Chapter3
Vince Vo
 
Java căn bản- Chapter1
Vince Vo
 
Hướng dẫn cài đặt Java
Vince Vo
 
Rama Ch13
Vince Vo
 
Rama Ch12
Vince Vo
 
Rama Ch10
Vince Vo
 
Rama Ch8
Vince Vo
 
Rama Ch9
Vince Vo
 
Rama Ch6
Vince Vo
 
Rama Ch5
Vince Vo
 
Rama Ch4
Vince Vo
 
Rama Ch3
Vince Vo
 
Rama Ch2
Vince Vo
 
Rama Ch1
Vince Vo
 

Recently uploaded (20)

PPTX
CATEGORIES OF NURSING PERSONNEL: HOSPITAL & COLLEGE
PRADEEP ABOTHU
 
PDF
The Different Types of Non-Experimental Research
Thelma Villaflores
 
PDF
0725.WHITEPAPER-UNIQUEWAYSOFPROTOTYPINGANDUXNOW.pdf
Thomas GIRARD, MA, CDP
 
PDF
CONCURSO DE POESIA “POETUFAS – PASSOS SUAVES PELO VERSO.pdf
Colégio Santa Teresinha
 
PDF
Women's Health: Essential Tips for Every Stage.pdf
Iftikhar Ahmed
 
PDF
QNL June Edition hosted by Pragya the official Quiz Club of the University of...
Pragya - UEM Kolkata Quiz Club
 
PPTX
PATIENT ASSIGNMENTS AND NURSING CARE RESPONSIBILITIES.pptx
PRADEEP ABOTHU
 
PPTX
How to Manage Large Scrollbar in Odoo 18 POS
Celine George
 
PDF
Aprendendo Arquitetura Framework Salesforce - Dia 03
Mauricio Alexandre Silva
 
PPTX
Stereochemistry-Optical Isomerism in organic compoundsptx
Tarannum Nadaf-Mansuri
 
PPTX
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
PPTX
MENINGITIS: NURSING MANAGEMENT, BACTERIAL MENINGITIS, VIRAL MENINGITIS.pptx
PRADEEP ABOTHU
 
PPTX
HUMAN RESOURCE MANAGEMENT: RECRUITMENT, SELECTION, PLACEMENT, DEPLOYMENT, TRA...
PRADEEP ABOTHU
 
PPTX
Unit 2 COMMERCIAL BANKING, Corporate banking.pptx
AnubalaSuresh1
 
PPTX
GRADE-3-PPT-EVE-2025-ENG-Q1-LESSON-1.pptx
EveOdrapngimapNarido
 
PPT
Talk on Critical Theory, Part II, Philosophy of Social Sciences
Soraj Hongladarom
 
PDF
DIGESTION OF CARBOHYDRATES,PROTEINS,LIPIDS
raviralanaresh2
 
PPTX
How to Set Up Tags in Odoo 18 - Odoo Slides
Celine George
 
PDF
The Constitution Review Committee (CRC) has released an updated schedule for ...
nservice241
 
PDF
Reconstruct, Restore, Reimagine: New Perspectives on Stoke Newington’s Histor...
History of Stoke Newington
 
CATEGORIES OF NURSING PERSONNEL: HOSPITAL & COLLEGE
PRADEEP ABOTHU
 
The Different Types of Non-Experimental Research
Thelma Villaflores
 
0725.WHITEPAPER-UNIQUEWAYSOFPROTOTYPINGANDUXNOW.pdf
Thomas GIRARD, MA, CDP
 
CONCURSO DE POESIA “POETUFAS – PASSOS SUAVES PELO VERSO.pdf
Colégio Santa Teresinha
 
Women's Health: Essential Tips for Every Stage.pdf
Iftikhar Ahmed
 
QNL June Edition hosted by Pragya the official Quiz Club of the University of...
Pragya - UEM Kolkata Quiz Club
 
PATIENT ASSIGNMENTS AND NURSING CARE RESPONSIBILITIES.pptx
PRADEEP ABOTHU
 
How to Manage Large Scrollbar in Odoo 18 POS
Celine George
 
Aprendendo Arquitetura Framework Salesforce - Dia 03
Mauricio Alexandre Silva
 
Stereochemistry-Optical Isomerism in organic compoundsptx
Tarannum Nadaf-Mansuri
 
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
MENINGITIS: NURSING MANAGEMENT, BACTERIAL MENINGITIS, VIRAL MENINGITIS.pptx
PRADEEP ABOTHU
 
HUMAN RESOURCE MANAGEMENT: RECRUITMENT, SELECTION, PLACEMENT, DEPLOYMENT, TRA...
PRADEEP ABOTHU
 
Unit 2 COMMERCIAL BANKING, Corporate banking.pptx
AnubalaSuresh1
 
GRADE-3-PPT-EVE-2025-ENG-Q1-LESSON-1.pptx
EveOdrapngimapNarido
 
Talk on Critical Theory, Part II, Philosophy of Social Sciences
Soraj Hongladarom
 
DIGESTION OF CARBOHYDRATES,PROTEINS,LIPIDS
raviralanaresh2
 
How to Set Up Tags in Odoo 18 - Odoo Slides
Celine George
 
The Constitution Review Committee (CRC) has released an updated schedule for ...
nservice241
 
Reconstruct, Restore, Reimagine: New Perspectives on Stoke Newington’s Histor...
History of Stoke Newington
 

Java căn bản - Chapter6

  • 1. Chapter 6 Repetition Statements
  • 2. Objectives After you have read and studied this chapter, you should be able to Implement repetition control in a program using while statements. Implement repetition control in a program using do-while statements. Implement a generic loop-and-a-half repetition control statement Implement repetition control in a program using for statements. 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 using the showConfirmDialog method of JOptionPane . (Optional) Write simple recursive methods
  • 3. Definition Repetition statements control a block of code to be executed for a fixed number of times or until a certain condition is met. Count-controlled repetitions terminate the execution of the block after it is executed for a fixed number of times. Sentinel-controlled repetitions terminate the execution of the block after one of the designated values called a sentinel is encountered. Repetition statements are called loop statements also.
  • 4. The while Statement int sum = 0, number = 1; while ( number <= 100 ) { sum = sum + number; number = number + 1; } These statements are executed as long as number is less than or equal to 100.
  • 5. Syntax for the while Statement while ( <boolean expression> ) <statement> while ( number <= 100 ) { sum = sum + number; number = number + 1; } Statement (loop body) Boolean Expression
  • 6. Control Flow of while int sum = 0, number = 1 number <= 100 ? false sum = sum + number; number = number + 1; true
  • 7. More Examples Keeps adding the numbers 1, 2, 3, … until the sum becomes larger than 1,000,000. Computes the product of the first 20 odd integers. int sum = 0, number = 1; while ( sum <= 1000000 ) { sum = sum + number; number = number + 1; } 1 int product = 1, number = 1, count = 20, lastNumber; lastNumber = 2 * count - 1; while ( number <= lastNumber ) { product = product * number; number = number + 2; } 2
  • 9. Example: Testing Input Data String inputStr; int age; inputStr = JOptionPane.showInputDialog ( null , &quot;Your Age (between 0 and 130):&quot; ) ; age = Integer.parseInt ( inputStr ) ; while ( age < 0 || age > 130 ) { JOptionPane.showMessageDialog ( null , &quot;An invalid age was entered. Please try again.&quot; ) ; inputStr = JOptionPane.showInputDialog ( null , &quot;Your Age (between 0 and 130):&quot; ) ; age = Integer.parseInt ( inputStr ) ; } Priming Read
  • 10. Useful Shorthand Operators sum = sum + number; sum += number; is equivalent to Meaning Usage Operator a = a % b; a %= b; %= a = a / b; a /= b; /= a = a * b; a *= b; *= a = a – b; a -= b; -= a = a + b; a += b; +=
  • 11. Watch Out for Pitfalls Watch out for the off-by-one error (OBOE). Make sure the loop body contains a statement that will eventually cause the loop to terminate. Make sure the loop repeats exactly the correct number of times. If you want to execute the loop body N times, then initialize the counter to 0 and use the test condition counter < N or initialize the counter to 1 and use the test condition counter <= N .
  • 12. Loop Pitfall - 1 Infinite Loops Both loops will not terminate because the boolean expressions will never become false. int count = 1; while ( count != 10 ) { count = count + 2; } 2 int product = 0; while ( product < 500000 ) { product = product * 5; } 1
  • 13. Overflow An infinite loop often results in an overflow error. 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.
  • 14. Loop Pitfall - 2 Using Real Numbers Loop 2 terminates, but Loop 1 does not because only an approximation of a real number can be stored in a computer memory. float count = 0.0f; while ( count != 1.0f ) { count = count + 0.33333333f; } //eight 3s 2 float count = 0.0f; while ( count != 1.0f ) { count = count + 0.3333333f; } //seven 3s 1
  • 15. Loop Pitfall – 2a int result = 0; double cnt = 1.0; while ( cnt <= 10.0 ){ cnt += 1.0; result++; } System.out.println ( result ) ; 1 int result = 0; double cnt = 0.0; while ( cnt <= 1.0 ){ cnt += 0.1; result++; } System.out.println ( result ) ; 2 Using Real Numbers Loop 1 prints out 10, as expected, but Loop 2 prints out 11. The value 0.1 cannot be stored precisely in computer memory. 10 11
  • 16. Loop Pitfall - 3 Goal: Execute the loop body 10 times. count = 1; while ( count < 10 ){ . . . count++; } 1 count = 0; while ( count <= 10 ){ . . . count++; } 3 count = 1; while ( count <= 10 ){ . . . count++; } 2 count = 0; while ( count < 10 ){ . . . count++; } 4 1 3 and exhibit off-by-one error.
  • 17. The do - while Statement int sum = 0, number = 1; do { sum += number; number++; } while ( sum <= 1000000 ); These statements are executed as long as sum is less than or equal to 1,000,000.
  • 18. Syntax for the do - while Statement do <statement> while ( <boolean expression> ) ; do { sum += number; number++; } while ( sum <= 1000000 ) ; Statement (loop body) Boolean Expression
  • 19. Control Flow of do - while int sum = 0, number = 1 sum += number; number++; sum <= 1000000 ? true false
  • 20. 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 .
  • 21. Example: Loop-and-a-Half Control String name; while ( true ){ name = JOptionPane.showInputDialog ( null , &quot;Your name&quot; ) ; if ( name.length () > 0 ) break ; JOptionPane.showMessageDialog ( null , &quot;Invalid Entry.&quot; + &quot;You must enter at least one character.&quot; ) ; }
  • 22. Pitfalls for Loop-and-a-Half 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. Multiple exit points. It is possible, although complex, to write a correct control loop with multiple exit points (break s). It is good practice to enforce the one-entry one-exit control flow.
  • 23. 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*/ &quot;Play Another Game?&quot; , /*dialog title*/ &quot;Confirmation&quot; , /*button options*/ JOptionPane.YES_NO_OPTION ) ;
  • 24. Example: Confirmation Dialog boolean keepPlaying = true ; int selection; while ( keepPlaying ){ //code to play one game comes here // . . . selection = JOptionPane.showConfirmDialog ( null , &quot;Play Another Game?&quot; , &quot;Confirmation&quot; , JOptionPane.YES_NO_OPTION ) ; keepPlaying = ( selection == JOptionPane.YES_OPTION ) ; }
  • 25. The for Statement int i, sum = 0, number; for ( i = 0; i < 20; i++ ) { number = scanner.nextInt ( ) ; sum += number; } These statements are executed for 20 times ( i = 0, 1, 2, … , 19 ).
  • 26. Syntax for the for Statement for ( <initialization>; <boolean expression>; <increment> ) <statement> for ( i = 0 ; i < 20 ; i++ ) { number = scanner.nextInt(); sum += number; } Initialization Boolean Expression Increment Statement (loop body)
  • 27. Control Flow of for i = 0; false number = . . . ; sum += number; true i ++; i < 20 ?
  • 28. More for Loop Examples i = 0, 5, 10, … , 95 j = 2, 4, 8, 16, 32 k = 100, 99, 98, 97, ..., 1 for (int i = 0; i < 100; i += 5) 1 for (int j = 2; j < 40; j *= 2) 2 for (int k = 100; k > 0; k--) ) 3
  • 29. The Nested-for Statement Nesting a for statement inside another for statement is commonly used technique in programming. Let’s generate the following table using nested-for statement.
  • 30. Generating the Table 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 ( “” ) ; } INNER OUTER
  • 31. 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 . The diagram shows the field width of 6. From Java 5.0, we can use the Formatter class. System.out ( PrintStream ) also includes the format method.
  • 32. The Formatter Class 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(&quot;%6d&quot;, num); This will output the value with the field width of 6.
  • 33. The format Method of Formatter The general syntax is format(<control string>, <expr1>, <expr2>, . . . ) Example: int num1 = 34, num2 = 9; int num3 = num1 + num2; formatter.format(&quot;%3d + %3d = %5d&quot;, num1, num2, num3);
  • 34. The format Method of PrintStream Instead of using the Formatter class directly, we can achieve the same result by using the format method of PrintStream (System.out) Formatter formatter = new Formatter(System.out); formatter.format(&quot;%6d&quot;, 498); is equivalent to System.out.format( &quot;%6d&quot;, 498 );
  • 35. Control Strings Integers % <field width> d Real Numbers % <field width> . <decimal places> f Strings % s For other data types and more formatting options, please consult the Java API for the Formatter class.
  • 36. Estimating the Execution Time In many situations, we would like to know how long it took to execute a piece of code. For example, Execution time of a loop statement that finds the greatest common divisor of two very large numbers, or Execution time of a loop statement to display all prime numbers between 1 and 100 million Execution time can be measured easily by using the Date class.
  • 37. Using the Date Class Here's one way to measure the execution time Date startTime = new Date(); //code you want to measure the execution time Date endTime = new Date(); long elapsedTimeInMilliSec = endTime.getTime() – startTime.getTime();
  • 38. Problem Statement Problem statement: Write an application that will play Hi-Lo games with the user. The objective of the game is for the user to guess the computer-generated secret number in the least number of tries. The secret number is an integer between 1 and 100, inclusive. When the user makes a guess, the program replies with HI or LO depending on whether the guess is higher or lower than the secret number. The maximum number of tries allowed for each game is six. The user can play as many games as she wants.
  • 39. Overall Plan Tasks: do { Task 1: generate a secret number ; Task 2: play one game ; } while ( the user wants to play ) ;
  • 40. Required Classes main class standard classes Ch6HiLo JOptionPane Math
  • 41. Development Steps We will develop this program in four steps: Start with a skeleton Ch6HiLo class. Add code to the Ch6HiLo class to play a game using a dummy secret number. Add code to the Ch6HiLo class to generate a random number. Finalize the code by tying up loose ends.
  • 42. Step 1 Design The topmost control logic of HiLo 1. describe the game rules ; 2. prompt the user to play a game or not ; while ( answer is yes ) { 3. generate the secret number ; 4. play one game ; 5. prompt the user to play another game or not ; }
  • 43. Step 1 Code Directory: Chapter6/Step1 Source Files: Ch6HiLo.java Program source file is too big to list here. From now on, we ask you to view the source files using your Java IDE.
  • 44. Step 1 Test In the testing phase, we run the program and verify confirm that the topmost control loop terminates correctly under different conditions. Play the game zero times one time one or more times
  • 45. Step 2 Design Implement the playGame method that plays one game of HiLo. Use a dummy secret number By using a fix number such as 45 as a dummy secret number, we will be able to test the correctness of the playGame method
  • 46. The Logic of playGame int guessCount = 0; do { get next guess ; guessCount++; if ( guess < secretNumber ) { print the hint LO ; } else if ( guess > secretNumber ) { print the hint HI ; } } while ( guessCount < number of guesses allowed && guess != secretNumber ) ; if ( guess == secretNumber ) { print the winning message ; } else { print the losing message ; }
  • 47. Step 2 Code Directory: Chapter6/Step2 Source Files: Ch6HiLo.java
  • 48. Step 2 Test We compile and run the program numerous times To test getNextGuess, enter a number less than 1 a number greater than 100 a number between 2 and 99 the number 1 and the number 100 To test playGame, enter a guess less than 45 a guess greater than 45 45 six wrong guesses
  • 49. Step 3 Design We complete the generateSecretNumber method. We want to generate a number between 1 and 100 inclusively. private void generateSecretNumber ( ) { double X = Math.random () ; secretNumber = ( int ) Math.floor ( X * 100 ) + 1; System.out.println ( &quot;Secret Number: &quot; + secretNumber ) ; // TEMP return secretNumber; }
  • 50. Step 3 Code Directory: Chapter6/Step3 Source Files: Ch6HiLo.java
  • 51. Step 3 Test We use a separate test driver to generate 1000 secret numbers. We run the program numerous times with different input values and check the results. Try both valid and invalid input values and confirm the response is appropriate
  • 52. Step 4: Finalize Program Completion Finish the describeRules method Remove all temporary statements Possible Extensions Allow the user to set her desired min and max for secret numbers Allow the user to set the number of guesses allowed Keep the score—the number of guesses made —while playing games and display the average score when the user quits the program

Editor's Notes

  • #3: We will study two forms of repetition statements in this lesson. They are while and do-while statement.
  • #4: In Chapter 5, we studied selection control statements. We will study in this chapter the second type of control statement, a repetition statement, that alters the sequential control flow. It controls the number of times a block of code is executed. In other words, a block of code is executed repeatedly until some condition occurs to stop the repetition. There are fundamentally two ways to stop the repetition—count-controlled and sentinel-controlled.
  • #5: The first repetition control we will study is the while statement. Here’s an example that computes the sum of integers from 1 to 100, inclusively. Note: there’s a closed form to compute the sum of 1 to 100, which is (100 * 101) / 2, so this repetition statement is a illustration purpose only.
  • #6: Here’s the general syntax of a while statement. As long as the &lt;boolean expression&gt; is true, the loop body is executed. Notice that the loop body may not be executed at all.
  • #7: This flowchart shows the control flow of the while statement. If the &lt;boolean expression&gt; is true, the loop body is executed and the control returns to the top. If the &lt;boolean expression&gt; is false, then the control flows to the next statement that follows this while statement.
  • #8: Variation on computing the product of the first 20 odd integers: int product = 1, number = 1, lastTerm = 20, count = 1; while ( count &lt;= lastTerm ) { product = product * (2 * number – 1); count = count + 1; }
  • #10: Here&apos;s a more practical example of using a repetition statement. This code will only accept a value greater than 0 but less than 130. If an input value is invalid, then the code will repeat until the valid input is read. Notice that the &apos;age&apos; variable must have a value before the boolean expression of the while statement can be evaluated. We therefore read the input value before the while test. This reading of input values before the test is called priming read. The loop body of this while statement is executed zero times if the input is valid the first time.
  • #11: When writing a repetition statement, we often see the statement that modifies the value of a variable in the form such as sum = sum + number. Because of a high occurrence of such statement, we can use shorthand operators. These shorthand assignment operators have precedence lower than any other arithmetic operators, so, for example, the statement sum *= a + b; is equivalent to sum = sum * (a + b);
  • #13: If you are not careful, you can easily end up writing an infinite loop. Make sure the test is written in such a way that the loop will terminate eventually.
  • #14: When an overflow error occurs, the execution of the program is terminated in almost all programming languages. When an overflow occurs in Java, a value that represents infinity (IEEE 754 infinity, to be precise) is assigned to a variable and no abnormal termination of a program will happen. Also, in Java an overflow occurs only with float and double variables; no overflow will happen with int variables. When you try to assign a value larger than the maximum possible integer an int variable can hold, the value “wraps around” and becomes a negative value. Whether the loop terminates or not because of an overflow error, the logic of the loop is still an infinite loop, and we must watch out for it. When you write a loop, you must make sure that the boolean expression of the loop will eventually become false.
  • #15: Although 1/3 + 1/3 + 1/3 == 1 is mathematically true, the expression 1.0/3.0 + 1.0/3.0 + 1.0/3.0 in computer language may or may not get evaluated to 1.0 depending on how precise the approximation is. In general, avoid using real numbers as counter variables because of this imprecision.
  • #16: Here&apos;s another example of using a double variable as a counter. The two loops are identical in concept, and therefore, should output the same result. They would if real numbers are stored precisely in computer memory. Because the value of 0.1 cannot be represented precisely in computer memory, the second one will actually print out 11, while the first one prints out 10, as expected.
  • #17: Yes, you can write the desired loop as count = 1; while (count != 10 ) { ... count++; } but this condition for stopping the count-controlled loop is dangerous. We already mentioned about the potential trap of an infinite loop.
  • #18: Here&apos;s an example of the second type of repetition statement called do-while. This sample code computes the sum of integers starting from 1 until the sum becomes greater than 1,000,000. The main difference between the while and do-while is the relative placement of the test. The test occurs before the loop body for the while statement, and the text occurs after the loop body for the do-while statement. Because of this characteristic, the loop body of a while statement is executed 0 or more times, while the loop body of the do-while statement is executed 1 or more times. In general, the while statement is more frequently used than the do–while statement.
  • #19: Here’s the general syntax of a do-while statement. As long as the &lt;boolean expression&gt; is true, the loop body is executed. Notice that the loop body is executed at least once.
  • #20: This flowchart shows the control flow of the do-while statement. If the &lt;boolean expression&gt; is true, the control returns to the top. If the &lt;boolean expression&gt; is false, then the control flows to the next statement that follows this do-while statement.
  • #22: This is a simple example of a loop-and-a-half control. Notice the priming read is avoided with this control.
  • #25: Here&apos;s an example of how we can use a confirmation dialog in a loop. At the end of the loop, we prompt the user to repeat the loop again or not.
  • #26: This is a basic example of a for statement. This for statement reads 20 integers and compute their sum.
  • #27: This shows the general syntax for the for statement. The &lt;initialization&gt; component also can include a declaration of the control variable. We can do something like this: for (int i = 0; i &lt; 10; i++) instead of int i; for (i = 0; i &lt; 10; i++)
  • #29: Here are some more examples of a for loop. Notice how the counting can go up or down by changing the increment expression accordingly.
  • #30: Just an if statement can be nested inside another if statement, we often nest for loops. For example, using a nest-for loop is the most appropriate way to generate a table such as the illustration.
  • #31: Here&apos;s how the table can be produced by a nested-for loop. For each value of width, length will range from 5 to 25 with an increment of 5. Here’s how the values for width and length change over the course of execution. width length 11 5 10 15 20 25 12 5 10 15 20 25 13 5 10 and so on…
  • #38: We can achieve the same result by using the currentTimeMillis method of the System class as long start = System.currentTimeMillis(); //code to measure long end = System.currentTimeMillis(); long elapsedTimeInMilliSec = end – start; To get the elasped time in seconds, we divide the milliseconds by 1000 long elapsedTimeInSec = elapsedTimeInMilliSec / 1000;
  • #40: As a part of the overall plan, we begin by identifying the main tasks for the program. Unlike the overall plan for the previous sample developments, we will use a pseudo code to express the top level logic of the program.
  • #41: The structure of this program is very simple. We will use two standard classes, one for input and output and another for generating random numbers.
  • #42: The second and the third steps correspond to the two major tasks identified in the overall plan.
  • #43: In the first step, we determine a little more detailed control logic than the one stated in the overall plan. For each of the five identified functions, we will define a method: describeRules, generateSecretNumber, playGame, and prompt.
  • #44: Please use your Java IDE to view the source files and run the program.
  • #45: Run the program and verify that the topmost control loop is functioning correctly.
  • #46: In order to verify whether our code is working correctly or not, we need to know what is the secret number. The easiest way to do this is to use a fixed number, such as 45, make the temporary generateRandomNumber to return this fixed number.
  • #47: Here&apos;s the playGame method expressed as a pseudocode.
  • #48: We implement the playGame and getNextGuess methods in this step.
  • #49: We need to verify the correctness of two methods: playGame and getNextGuess. Try all cases presented here and confirm that you get the expected responses.
  • #50: Notice that we have one temporary statement to output the value of secretNumber. We include it for the testing purpose, i.e., we need to check the numbers generated are valid.
  • #52: As always, we run the final test by running the program numerous times trying out as many variations as possible. Before testing the generateSecretNumber method as a part of the final program, we will use a separate test driver to generate 1000 (or more) secret numbers and verify that they are valid. class TestRandom { public static void main (String[] args) { int N = 1000, count = 0, number; double X; do { count++; X = Math.random(); number = (int) Math.floor( X * 100 ) + 1; } while ( count &lt; N &amp;&amp; 1 &lt;= number &amp;&amp; number &lt;= 100 ); if ( number &lt; 1 || number &gt; 100 ) { System.out.println(&amp;quot;Error: &amp;quot; + number); } else { System.out.println(&amp;quot;Okay&amp;quot;); } } }