SlideShare una empresa de Scribd logo
1 de 52
Chapter 6 Repetition Statements
Objectives ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Definition ,[object Object],[object Object],[object Object],[object Object]
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 ,[object Object],[object Object],[object Object],[object Object]
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 ,[object Object],[object Object],[object Object]
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 ,[object Object],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 ,[object Object],[object Object]
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 ,[object Object],[object Object],[object Object]
Confirmation Dialog ,[object Object],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 ,[object Object],[object Object]
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 ,[object Object],[object Object]
The Formatter Class ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
The format Method of Formatter ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
The format Method of PrintStream ,[object Object],[object Object],[object Object],[object Object],[object Object]
Control Strings ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Estimating the Execution Time ,[object Object],[object Object],[object Object],[object Object]
Using the Date Class ,[object Object],Date startTime = new Date(); //code you want to measure the execution time Date endTime = new Date(); long elapsedTimeInMilliSec = endTime.getTime() – startTime.getTime();
Problem Statement ,[object Object],[object Object]
Overall Plan ,[object Object],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 ,[object Object],[object Object],[object Object],[object Object],[object Object]
Step 1 Design ,[object Object],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 ,[object Object],[object Object],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 ,[object Object],[object Object],[object Object],[object Object],[object Object]
Step 2 Design ,[object Object],[object Object],[object Object]
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 ,[object Object],[object Object]
Step 2 Test ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Step 3 Design ,[object Object],[object Object],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 ,[object Object],[object Object]
Step 3 Test ,[object Object],[object Object],[object Object]
Step 4: Finalize ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]

Más contenido relacionado

La actualidad más candente

FP 201 Unit 2 - Part 3
FP 201 Unit 2 - Part 3FP 201 Unit 2 - Part 3
FP 201 Unit 2 - Part 3
rohassanie
 
FP 201 Unit 3
FP 201 Unit 3 FP 201 Unit 3
FP 201 Unit 3
rohassanie
 
FP 201 - Unit 3 Part 2
FP 201 - Unit 3 Part 2FP 201 - Unit 3 Part 2
FP 201 - Unit 3 Part 2
rohassanie
 

La actualidad más candente (20)

Chap 5 c++
Chap 5 c++Chap 5 c++
Chap 5 c++
 
12. Exception Handling
12. Exception Handling 12. Exception Handling
12. Exception Handling
 
Python unit 3 and Unit 4
Python unit 3 and Unit 4Python unit 3 and Unit 4
Python unit 3 and Unit 4
 
Python Programming Essentials - M16 - Control Flow Statements and Loops
Python Programming Essentials - M16 - Control Flow Statements and LoopsPython Programming Essentials - M16 - Control Flow Statements and Loops
Python Programming Essentials - M16 - Control Flow Statements and Loops
 
C++ programming
C++ programmingC++ programming
C++ programming
 
Working of while loop
Working of while loopWorking of while loop
Working of while loop
 
Chap 5 c++
Chap 5 c++Chap 5 c++
Chap 5 c++
 
FP 201 Unit 2 - Part 3
FP 201 Unit 2 - Part 3FP 201 Unit 2 - Part 3
FP 201 Unit 2 - Part 3
 
Operators and Control Statements in Python
Operators and Control Statements in PythonOperators and Control Statements in Python
Operators and Control Statements in Python
 
03. Operators Expressions and statements
03. Operators Expressions and statements03. Operators Expressions and statements
03. Operators Expressions and statements
 
Python
PythonPython
Python
 
FP 201 Unit 3
FP 201 Unit 3 FP 201 Unit 3
FP 201 Unit 3
 
130707833146508191
130707833146508191130707833146508191
130707833146508191
 
06 Loops
06 Loops06 Loops
06 Loops
 
FP 201 - Unit 3 Part 2
FP 201 - Unit 3 Part 2FP 201 - Unit 3 Part 2
FP 201 - Unit 3 Part 2
 
GE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python ProgrammingGE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python Programming
 
Functional Programming in C#
Functional Programming in C#Functional Programming in C#
Functional Programming in C#
 
Nesting of for loops using C++
Nesting of for loops using C++Nesting of for loops using C++
Nesting of for loops using C++
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 
Unit2 control statements
Unit2 control statementsUnit2 control statements
Unit2 control statements
 

Destacado

Java căn bản - Chapter4
Java căn bản - Chapter4Java căn bản - Chapter4
Java căn bản - Chapter4
Vince Vo
 
Java căn bản - Chapter2
Java căn bản - Chapter2Java căn bản - Chapter2
Java căn bản - Chapter2
Vince Vo
 
Java căn bản - Chapter7
Java căn bản - Chapter7Java căn bản - Chapter7
Java căn bản - Chapter7
Vince Vo
 
Java căn bản - Chapter12
Java căn bản - Chapter12Java căn bản - Chapter12
Java căn bản - Chapter12
Vince Vo
 

Destacado (8)

Java căn bản - Chapter4
Java căn bản - Chapter4Java căn bản - Chapter4
Java căn bản - Chapter4
 
Rama Ch11
Rama Ch11Rama Ch11
Rama Ch11
 
Rama Ch14
Rama Ch14Rama Ch14
Rama Ch14
 
Rama Ch12
Rama Ch12Rama Ch12
Rama Ch12
 
Java căn bản - Chapter2
Java căn bản - Chapter2Java căn bản - Chapter2
Java căn bản - Chapter2
 
Java căn bản - Chapter7
Java căn bản - Chapter7Java căn bản - Chapter7
Java căn bản - Chapter7
 
Rama Ch7
Rama Ch7Rama Ch7
Rama Ch7
 
Java căn bản - Chapter12
Java căn bản - Chapter12Java căn bản - Chapter12
Java căn bản - Chapter12
 

Similar a Java căn bản - Chapter6

C Sharp Jn (3)
C Sharp Jn (3)C Sharp Jn (3)
C Sharp Jn (3)
jahanullah
 
Slide07 repetitions
Slide07 repetitionsSlide07 repetitions
Slide07 repetitions
altwirqi
 
C++ control structure
C++ control structureC++ control structure
C++ control structure
bluejayjunior
 
Verilog Lecture3 hust 2014
Verilog Lecture3 hust 2014Verilog Lecture3 hust 2014
Verilog Lecture3 hust 2014
Béo Tú
 

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

06.Loops
06.Loops06.Loops
06.Loops
 
C Sharp Jn (3)
C Sharp Jn (3)C Sharp Jn (3)
C Sharp Jn (3)
 
Slide07 repetitions
Slide07 repetitionsSlide07 repetitions
Slide07 repetitions
 
Programming fundamental 02
Programming fundamental 02Programming fundamental 02
Programming fundamental 02
 
Repetition Structure
Repetition StructureRepetition Structure
Repetition Structure
 
Loops
LoopsLoops
Loops
 
Control structure of c
Control structure of cControl structure of c
Control structure of c
 
Looping
LoopingLooping
Looping
 
Loops in c language
Loops in c languageLoops in c language
Loops in c language
 
Loops in c language
Loops in c languageLoops in c language
Loops in c language
 
Lecture 4
Lecture 4Lecture 4
Lecture 4
 
ICP - Lecture 9
ICP - Lecture 9ICP - Lecture 9
ICP - Lecture 9
 
C++ control structure
C++ control structureC++ control structure
C++ control structure
 
Lec7 - Loops updated.pptx
Lec7 - Loops updated.pptxLec7 - Loops updated.pptx
Lec7 - Loops updated.pptx
 
Verilog Lecture3 hust 2014
Verilog Lecture3 hust 2014Verilog Lecture3 hust 2014
Verilog Lecture3 hust 2014
 
Ch3 repetition
Ch3 repetitionCh3 repetition
Ch3 repetition
 
Control Structures in C
Control Structures in CControl Structures in C
Control Structures in C
 
C++ loop
C++ loop C++ loop
C++ loop
 
4th_Ed_Ch03.pdf
4th_Ed_Ch03.pdf4th_Ed_Ch03.pdf
4th_Ed_Ch03.pdf
 
Lecture 3
Lecture 3Lecture 3
Lecture 3
 

Más de Vince Vo

Java căn bản - Chapter13
Java căn bản - Chapter13Java căn bản - Chapter13
Java căn bản - Chapter13
Vince Vo
 
Java căn bản - Chapter10
Java căn bản - Chapter10Java căn bản - Chapter10
Java căn bản - Chapter10
Vince Vo
 
Java căn bản - Chapter9
Java căn bản - Chapter9Java căn bản - Chapter9
Java căn bản - Chapter9
Vince Vo
 
Java căn bản - Chapter8
Java căn bản - Chapter8Java căn bản - Chapter8
Java căn bản - Chapter8
Vince Vo
 
Java căn bản - Chapter5
Java căn bản - Chapter5Java căn bản - Chapter5
Java căn bản - Chapter5
Vince Vo
 
Java căn bản - Chapter3
Java căn bản - Chapter3Java căn bản - Chapter3
Java căn bản - Chapter3
Vince Vo
 
Java căn bản- Chapter1
Java  căn bản- Chapter1Java  căn bản- Chapter1
Java căn bản- Chapter1
Vince Vo
 
Hướng dẫn cài đặt Java
Hướng dẫn cài đặt JavaHướng dẫn cài đặt Java
Hướng dẫn cài đặt Java
Vince Vo
 

Más de Vince Vo (19)

Java căn bản - Chapter13
Java căn bản - Chapter13Java căn bản - Chapter13
Java căn bản - Chapter13
 
Java căn bản - Chapter10
Java căn bản - Chapter10Java căn bản - Chapter10
Java căn bản - Chapter10
 
Java căn bản - Chapter9
Java căn bản - Chapter9Java căn bản - Chapter9
Java căn bản - Chapter9
 
Java căn bản - Chapter8
Java căn bản - Chapter8Java căn bản - Chapter8
Java căn bản - Chapter8
 
Java căn bản - Chapter5
Java căn bản - Chapter5Java căn bản - Chapter5
Java căn bản - Chapter5
 
Java căn bản - Chapter3
Java căn bản - Chapter3Java căn bản - Chapter3
Java căn bản - Chapter3
 
Java căn bản- Chapter1
Java  căn bản- Chapter1Java  căn bản- Chapter1
Java căn bản- Chapter1
 
Hướng dẫn cài đặt Java
Hướng dẫn cài đặt JavaHướng dẫn cài đặt Java
Hướng dẫn cài đặt Java
 
Rama Ch13
Rama Ch13Rama Ch13
Rama Ch13
 
Rama Ch12
Rama Ch12Rama Ch12
Rama Ch12
 
Rama Ch10
Rama Ch10Rama Ch10
Rama Ch10
 
Rama Ch8
Rama Ch8Rama Ch8
Rama Ch8
 
Rama Ch9
Rama Ch9Rama Ch9
Rama Ch9
 
Rama Ch6
Rama Ch6Rama Ch6
Rama Ch6
 
Rama Ch5
Rama Ch5Rama Ch5
Rama Ch5
 
Rama Ch4
Rama Ch4Rama Ch4
Rama Ch4
 
Rama Ch3
Rama Ch3Rama Ch3
Rama Ch3
 
Rama Ch2
Rama Ch2Rama Ch2
Rama Ch2
 
Rama Ch1
Rama Ch1Rama Ch1
Rama Ch1
 

Último

The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 

Último (20)

Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptx
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 

Java căn bản - Chapter6

  • 1. Chapter 6 Repetition Statements
  • 2.
  • 3.
  • 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.
  • 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.
  • 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.
  • 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.
  • 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.
  • 23.
  • 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.
  • 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.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40. Required Classes main class standard classes Ch6HiLo JOptionPane Math
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 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.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.

Notas del editor

  1. We will study two forms of repetition statements in this lesson. They are while and do-while statement.
  2. 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.
  3. 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.
  4. 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.
  5. 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.
  6. 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; }
  7. 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.
  8. 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);
  9. 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.
  10. 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.
  11. 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.
  12. 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.
  13. 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.
  14. 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.
  15. 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.
  16. 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.
  17. This is a simple example of a loop-and-a-half control. Notice the priming read is avoided with this control.
  18. 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.
  19. This is a basic example of a for statement. This for statement reads 20 integers and compute their sum.
  20. 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++)
  21. Here are some more examples of a for loop. Notice how the counting can go up or down by changing the increment expression accordingly.
  22. 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.
  23. 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…
  24. 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;
  25. 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.
  26. 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.
  27. The second and the third steps correspond to the two major tasks identified in the overall plan.
  28. 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.
  29. Please use your Java IDE to view the source files and run the program.
  30. Run the program and verify that the topmost control loop is functioning correctly.
  31. 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.
  32. Here&apos;s the playGame method expressed as a pseudocode.
  33. We implement the playGame and getNextGuess methods in this step.
  34. 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.
  35. 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.
  36. 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;); } } }