SlideShare a Scribd company logo
Chapter 4
Introduction to Control
Statements
Fundamentals of Java
Fundamentals of Java
2
Objectives
 Use the increment and decrement operators.
 Use standard math methods.
 Use if and if-else statements to make
choices.
Fundamentals of Java
3
Objectives (cont.)
 Use while and for loops to repeat a
process.
 Construct appropriate conditions for control
statements using relational operators.
 Detect and correct common loop errors.
Fundamentals of Java
4
Vocabulary
 Control statements
 Counter
 Count-controlled loop
 Entry-controlled loop
 Flowchart
 Infinite loop
Fundamentals of Java
5
Vocabulary (cont.)
 Iteration
 Off-by-one error
 Overloading
 Sentinel
 Task-controlled loop
Fundamentals of Java
6
Additional Operators
 Extended assignment operators
– Assignment operator combined with
arithmetic and concatenation operators
Fundamentals of Java
7
Additional Operators (cont.)
 Increment operator: ++
– Increase value of operand by 1
 Decrement operator: --
– Decrease value of operand by 1
Fundamentals of Java
8
Standard Classes and Methods:
The Math Class
Table 4-1: Seven methods in the Math class
Fundamentals of Java
9
Standard Classes and Methods:
The Math Class (cont.)
 The two abs() methods are overloaded.
– Overloaded: Multiple methods in the same class
with the same name
 Using sqrt() method example:
Fundamentals of Java
10
Standard Classes and Methods:
The Math Class (cont.)
 Math class methods example:
Fundamentals of Java
11
Standard Classes and Methods:
The Random Class
 Random number generator: Returns
numbers chosen at random from a pre-
designated interval
Table 4-2: Methods in the Random class
Fundamentals of Java
12
A Visit to the Farm
Fundamentals of Java
13
The if and if-else Statements
 Principal forms:
Fundamentals of Java
14
The if and if-else Statements
(cont.)
 Additional forms:
Fundamentals of Java
15
The if and if-else Statements
(cont.)
 Better to over-use braces than under-use
them
– Can help to eliminate logic errors
 Condition of an if statement must be a
Boolean expression
– Evaluates to true or false
 A flowchart can be used to illustrate the
behavior of if-else statements.
Fundamentals of Java
16
The if and if-else Statements
(cont.)
Figure 4-1: Flowcharts for the if and if-else statements
Fundamentals of Java
17
The if and if-else Statements
(cont.)
 Examples of if statements:
Fundamentals of Java
18
The if and if-else Statements
(cont.)
Table 4-3: Relational operators
Fundamentals of Java
19
The if and if-else Statements
(cont.): Checking Input for Validity
Example 4.1: Computes the area of a circle if the
radius >= 0 or otherwise displays an error message
Fundamentals of Java
20
The while Statement
 Provides a looping mechanism
– Executes statements repeatedly for as long as
some condition remains true
Fundamentals of Java
21
The while Statement (cont.)
Figure 4-2: Flowchart for a while statement
Fundamentals of Java
22
The while Statement (cont.)
 Example:
 Counter-controlled loop:
– cntr is the counter
– Loop repeats a determined number of times
Fundamentals of Java
23
The while Statement (cont.)
 Tracing: Track value of variables through
each iteration of the loop
Table 4-4: Trace of how variables change
on each iteration through a loop
Fundamentals of Java
24
The while Statement (cont.)
 Counting backward:
Fundamentals of Java
25
The while Statement (cont.)
 Task-controlled loop: Continues to
execute until some task is accomplished
Fundamentals of Java
26
The while Statement (cont.)
 Common structure of a while loop:
Fundamentals of Java
27
The while Statement (cont.)
Example 4.2: Compute and display the factorial of n
Fundamentals of Java
28
The for statement
 Combines counter initialization, condition test,
and update into a single expression
 Easy to create count-controlled loops
Fundamentals of Java
29
The for statement (cont.)
 Example:
Fundamentals of Java
30
The for statement (cont.)
 Count-controlled input:
Fundamentals of Java
31
The for statement (cont.)
 Better to declare the loop control variable
within the loop header
– Only visible within the loop
– Variable name can be reused later in other loops
Fundamentals of Java
32
The for statement (cont.)
 Both for loops and while loops are entry-
controlled loops.
– Condition tested at top of loop on each pass
 Choosing a for loop versus a while loop is
often a matter of style.
– for loop advantages:
Can declare loop control variable in header
Initialization, condition, and update in one line of
code
Fundamentals of Java
33
Nested Control Statements and the
break Statement
 Control statements may be nested.
Fundamentals of Java
34
Nested Control Statements and the
break Statement (cont.)
 break statement: Prematurely end a loop
Fundamentals of Java
35
Nested Control Statements and the
break Statement (cont.)
 Sentinel-controlled input: Continue a loop
until a sentinel variable has a specific value
Fundamentals of Java
36
Using Loops with Text Files
 Advantages of using text files versus input
from a human user:
– Data sets can be much larger.
– Data input quickly, with less chance of error.
– Data can be used repeatedly.
 Data files can be created by hand in a text
editor or generated by a program.
Fundamentals of Java
37
Using Loops with Text Files (cont.)
 Text file format:
– If data is numerical, numbers must be separated
by white space.
– Must be an end-of-file character
Used by program to determine whether it is done
reading data
 When an error occurs at run-time, the JVM
throws an exception.
– IOException thrown if error occurs during file
operations
Fundamentals of Java
38
Using Loops with Text Files (cont.)
Example 4.3: Computes and displays the average
of a file of floating-point numbers
Fundamentals of Java
39
Using Loops with Text Files (cont.)
Example 4.4: Inputs a text file of integers and
writes these to an output file without the zeroes
Fundamentals of Java
40
Errors in Loops
 May occur in initializing statements,
terminating conditions, body statements, or
update statements
 Initialization error: Failure to initialize or
initializes to incorrect value
 Off-by-one error: Loop iterates one too
many or one too few times
Fundamentals of Java
41
Errors in Loops (cont.)
 Infinite loop: Error in the terminating
condition
– Loop never terminates
 Errors in loop body affect whether the loop
completes its task correctly or at all.
 Update error: Update statements in wrong
place may affect calculations
– Failing to update at all results in an infinite loop.
Fundamentals of Java
42
Errors in Loops (cont.)
 Effects of limited floating-point precision:
When using floating-point variables as loop
control variables, you must understand that
not all values can be represented.
– Better not to use == or != in condition
statement under these conditions
Fundamentals of Java
43
Errors in Loops (cont.)
 Debugging loops:
– If an error is suspected, make sure that:
Variables are initialized before entering the loop
The terminating condition stops the iterations
when the test variables have reached the
intended limit
The statements in the body are correct
Fundamentals of Java
44
Errors in Loops (cont.)
 Debugging loops (cont.):
– If an error is suspected, make sure that:
The update statements are positioned correctly
and modify the test variables so that they
eventually pass the limits tested in the
terminating condition
Fundamentals of Java
45
Graphics and GUIs: I/O Dialog
Boxes and Loops
 A convenient way to accept input from a user
is to pop up an input dialog box.
– Use JOptionPane.showInputDialog().
Figure 4-4: Input dialog box
Fundamentals of Java
46
Graphics and GUIs: I/O Dialog
Boxes and Loops (cont.)
 If expected input is a number, must use
Integer.parseInt() or
Double.parseDouble()
 To output a message, use a message
dialog box.
– JOptionPane.showMessageDialog(
anObserver, aString)
Fundamentals of Java
47
Graphics and GUIs: I/O Dialog
Boxes and Loops (cont.)
Example 4.5: CircleArea with dialog I/O
Fundamentals of Java
48
Graphics and GUIs: I/O Dialog
Boxes and Loops (cont.)
Figure 4.5: Dialog I/O user interface for the circle area program
Fundamentals of Java
49
Graphics and GUIs: I/O Dialog
Boxes and Loops (cont.)
 Setting up multiple panels:
– Can use a loop to initialize and install panels
 Setting the preferred size of a panel:
– Use JPanel class’s setPreferredSize()
method.
– JFrame class’s pack() method will cause the
window to adjust its size to exactly fit the
preferred size of any contained panels.
Fundamentals of Java
50
Graphics and GUIs: I/O Dialog
Boxes and Loops (cont.)
Example 4-7: Color panel whose background is a
color provided by the client. A client-specified
preferred size is optional.
Fundamentals of Java
51
Design, Testing, and Debugging
Hints
 Most errors involving selection statements
and loops are not syntax errors.
 The presence or absence of the {} symbols
can seriously affect the logic of a selection
statement or loop.
 When testing programs that use if or if-
else statements, use test data that forces
the program to exercise all logical branches.
Fundamentals of Java
52
Design, Testing, and Debugging
Hints (cont.)
 Use an if-else statement rather than two
if statements when the alternative courses
of action are mutually exclusive.
 When testing a loop, be sure to use limit
values as well as typical values.
 Be sure to check entry conditions and exit
conditions for each loop.
Fundamentals of Java
53
Design, Testing, and Debugging
Hints (cont.)
 For a loop with errors, use debugging output
statements to verify the values of the control
variable on each pass through the loop.
 Text files are convenient to use when the
data set is large, when the same data set
must be used repeatedly with different
programs, and when these data must be
saved permanently.
Fundamentals of Java
54
Summary
 Java has operators for extended assignment
and for increment and decrement.
 The Math class provides several useful
methods, such as sqrt and abs.
 The Random class allows you to generate
random integers and floating-point numbers.
 if and if-else statements are used to
make one-way and two-way decisions.
Fundamentals of Java
55
Summary (cont.)
 The comparison operators, such as ==, <=,
and >=, return Boolean values that can serve
as conditions for control statements.
 The while loop allows the program to run a
set of statements repeatedly until a condition
becomes false.
 The for loop is a more concise version of
the while loop.
Fundamentals of Java
56
Summary (cont.)
 Other control statements, such as an if
statement, can be nested within loops.
 A break statement can be used with an if
statement to terminate a loop early.
 Many kinds of logic errors can occur in loops.
– Off-by-one error
– Infinite loop

More Related Content

Similar to Control statements in Java Programming Language (20)

OOP - basics.pdf
OOP - basics.pdf
AbdallahN
 
Java chapter 3
Java chapter 3
Abdii Rashid
 
Java
Java
Aashish Jain
 
Cso gaddis java_chapter4
Cso gaddis java_chapter4
mlrbrown
 
JAVA.pptx
JAVA.pptx
DrRSuganyaRengaraj
 
JAVA.pptx
JAVA.pptx
DrRSuganyaRengaraj
 
data types.pdf
data types.pdf
HarshithaGowda914171
 
C Programming Looping Statements For Students
C Programming Looping Statements For Students
SoumyaKantiSarkar2
 
Ch4_part1.ppt
Ch4_part1.ppt
RuthikReddyGarlapati
 
Ch4_part1.ppt
Ch4_part1.ppt
ssuserc70988
 
Unit I Advanced Java Programming Course
Unit I Advanced Java Programming Course
parveen837153
 
JPC#8 Introduction to Java Programming
JPC#8 Introduction to Java Programming
Pathomchon Sriwilairit
 
DSA 103 Object Oriented Programming :: Week 3
DSA 103 Object Oriented Programming :: Week 3
Ferdin Joe John Joseph PhD
 
00_Introduction to Java.ppt
00_Introduction to Java.ppt
HongAnhNguyn285885
 
Java teaching ppt for the freshers in colleeg.ppt
Java teaching ppt for the freshers in colleeg.ppt
vvsofttechsolution
 
Control statements in java
Control statements in java
Madishetty Prathibha
 
Introduction to Java Programming Part 2
Introduction to Java Programming Part 2
university of education,Lahore
 
Java_Tutorial_Introduction_to_Core_java.ppt
Java_Tutorial_Introduction_to_Core_java.ppt
Govind Samleti
 
Java Tutorial
Java Tutorial
ArnaldoCanelas
 
Javatut1
Javatut1
desaigeeta
 

More from ssuser5d6130 (7)

packages in java programming language ppt
packages in java programming language ppt
ssuser5d6130
 
Arrays in java programming language slides
Arrays in java programming language slides
ssuser5d6130
 
Arrays in Java Programming Language slides
Arrays in Java Programming Language slides
ssuser5d6130
 
Arrays in Java Programming Language slides
Arrays in Java Programming Language slides
ssuser5d6130
 
Lecture_5_Method_overloading_Final.pptx in Java
Lecture_5_Method_overloading_Final.pptx in Java
ssuser5d6130
 
Inner classes or nested classes in Java Program
Inner classes or nested classes in Java Program
ssuser5d6130
 
API-led.pptx
API-led.pptx
ssuser5d6130
 
packages in java programming language ppt
packages in java programming language ppt
ssuser5d6130
 
Arrays in java programming language slides
Arrays in java programming language slides
ssuser5d6130
 
Arrays in Java Programming Language slides
Arrays in Java Programming Language slides
ssuser5d6130
 
Arrays in Java Programming Language slides
Arrays in Java Programming Language slides
ssuser5d6130
 
Lecture_5_Method_overloading_Final.pptx in Java
Lecture_5_Method_overloading_Final.pptx in Java
ssuser5d6130
 
Inner classes or nested classes in Java Program
Inner classes or nested classes in Java Program
ssuser5d6130
 
Ad

Recently uploaded (20)

How the US Navy Approaches DevSecOps with Raise 2.0
How the US Navy Approaches DevSecOps with Raise 2.0
Anchore
 
Zoneranker’s Digital marketing solutions
Zoneranker’s Digital marketing solutions
reenashriee
 
Porting Qt 5 QML Modules to Qt 6 Webinar
Porting Qt 5 QML Modules to Qt 6 Webinar
ICS
 
Step by step guide to install Flutter and Dart
Step by step guide to install Flutter and Dart
S Pranav (Deepu)
 
Transmission Media. (Computer Networks)
Transmission Media. (Computer Networks)
S Pranav (Deepu)
 
How to Choose the Right Web Development Agency.pdf
How to Choose the Right Web Development Agency.pdf
Creative Fosters
 
AI and Deep Learning with NVIDIA Technologies
AI and Deep Learning with NVIDIA Technologies
SandeepKS52
 
Agile Software Engineering Methodologies
Agile Software Engineering Methodologies
Gaurav Sharma
 
OpenTelemetry 101 Cloud Native Barcelona
OpenTelemetry 101 Cloud Native Barcelona
Imma Valls Bernaus
 
dp-700 exam questions sample docume .pdf
dp-700 exam questions sample docume .pdf
pravkumarbiz
 
DevOps for AI: running LLMs in production with Kubernetes and KubeFlow
DevOps for AI: running LLMs in production with Kubernetes and KubeFlow
Aarno Aukia
 
Generative Artificial Intelligence and its Applications
Generative Artificial Intelligence and its Applications
SandeepKS52
 
Advanced Token Development - Decentralized Innovation
Advanced Token Development - Decentralized Innovation
arohisinghas720
 
Artificial Intelligence Applications Across Industries
Artificial Intelligence Applications Across Industries
SandeepKS52
 
Meet You in the Middle: 1000x Performance for Parquet Queries on PB-Scale Dat...
Meet You in the Middle: 1000x Performance for Parquet Queries on PB-Scale Dat...
Alluxio, Inc.
 
FME as an Orchestration Tool - Peak of Data & AI 2025
FME as an Orchestration Tool - Peak of Data & AI 2025
Safe Software
 
IMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptx
IMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptx
usmanch7829
 
AI-Powered Compliance Solutions for Global Regulations | Certivo
AI-Powered Compliance Solutions for Global Regulations | Certivo
certivoai
 
Plooma is a writing platform to plan, write, and shape books your way
Plooma is a writing platform to plan, write, and shape books your way
Plooma
 
SAP PM Module Level-IV Training Complete.ppt
SAP PM Module Level-IV Training Complete.ppt
MuhammadShaheryar36
 
How the US Navy Approaches DevSecOps with Raise 2.0
How the US Navy Approaches DevSecOps with Raise 2.0
Anchore
 
Zoneranker’s Digital marketing solutions
Zoneranker’s Digital marketing solutions
reenashriee
 
Porting Qt 5 QML Modules to Qt 6 Webinar
Porting Qt 5 QML Modules to Qt 6 Webinar
ICS
 
Step by step guide to install Flutter and Dart
Step by step guide to install Flutter and Dart
S Pranav (Deepu)
 
Transmission Media. (Computer Networks)
Transmission Media. (Computer Networks)
S Pranav (Deepu)
 
How to Choose the Right Web Development Agency.pdf
How to Choose the Right Web Development Agency.pdf
Creative Fosters
 
AI and Deep Learning with NVIDIA Technologies
AI and Deep Learning with NVIDIA Technologies
SandeepKS52
 
Agile Software Engineering Methodologies
Agile Software Engineering Methodologies
Gaurav Sharma
 
OpenTelemetry 101 Cloud Native Barcelona
OpenTelemetry 101 Cloud Native Barcelona
Imma Valls Bernaus
 
dp-700 exam questions sample docume .pdf
dp-700 exam questions sample docume .pdf
pravkumarbiz
 
DevOps for AI: running LLMs in production with Kubernetes and KubeFlow
DevOps for AI: running LLMs in production with Kubernetes and KubeFlow
Aarno Aukia
 
Generative Artificial Intelligence and its Applications
Generative Artificial Intelligence and its Applications
SandeepKS52
 
Advanced Token Development - Decentralized Innovation
Advanced Token Development - Decentralized Innovation
arohisinghas720
 
Artificial Intelligence Applications Across Industries
Artificial Intelligence Applications Across Industries
SandeepKS52
 
Meet You in the Middle: 1000x Performance for Parquet Queries on PB-Scale Dat...
Meet You in the Middle: 1000x Performance for Parquet Queries on PB-Scale Dat...
Alluxio, Inc.
 
FME as an Orchestration Tool - Peak of Data & AI 2025
FME as an Orchestration Tool - Peak of Data & AI 2025
Safe Software
 
IMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptx
IMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptx
usmanch7829
 
AI-Powered Compliance Solutions for Global Regulations | Certivo
AI-Powered Compliance Solutions for Global Regulations | Certivo
certivoai
 
Plooma is a writing platform to plan, write, and shape books your way
Plooma is a writing platform to plan, write, and shape books your way
Plooma
 
SAP PM Module Level-IV Training Complete.ppt
SAP PM Module Level-IV Training Complete.ppt
MuhammadShaheryar36
 
Ad

Control statements in Java Programming Language

  • 1. Chapter 4 Introduction to Control Statements Fundamentals of Java
  • 2. Fundamentals of Java 2 Objectives  Use the increment and decrement operators.  Use standard math methods.  Use if and if-else statements to make choices.
  • 3. Fundamentals of Java 3 Objectives (cont.)  Use while and for loops to repeat a process.  Construct appropriate conditions for control statements using relational operators.  Detect and correct common loop errors.
  • 4. Fundamentals of Java 4 Vocabulary  Control statements  Counter  Count-controlled loop  Entry-controlled loop  Flowchart  Infinite loop
  • 5. Fundamentals of Java 5 Vocabulary (cont.)  Iteration  Off-by-one error  Overloading  Sentinel  Task-controlled loop
  • 6. Fundamentals of Java 6 Additional Operators  Extended assignment operators – Assignment operator combined with arithmetic and concatenation operators
  • 7. Fundamentals of Java 7 Additional Operators (cont.)  Increment operator: ++ – Increase value of operand by 1  Decrement operator: -- – Decrease value of operand by 1
  • 8. Fundamentals of Java 8 Standard Classes and Methods: The Math Class Table 4-1: Seven methods in the Math class
  • 9. Fundamentals of Java 9 Standard Classes and Methods: The Math Class (cont.)  The two abs() methods are overloaded. – Overloaded: Multiple methods in the same class with the same name  Using sqrt() method example:
  • 10. Fundamentals of Java 10 Standard Classes and Methods: The Math Class (cont.)  Math class methods example:
  • 11. Fundamentals of Java 11 Standard Classes and Methods: The Random Class  Random number generator: Returns numbers chosen at random from a pre- designated interval Table 4-2: Methods in the Random class
  • 12. Fundamentals of Java 12 A Visit to the Farm
  • 13. Fundamentals of Java 13 The if and if-else Statements  Principal forms:
  • 14. Fundamentals of Java 14 The if and if-else Statements (cont.)  Additional forms:
  • 15. Fundamentals of Java 15 The if and if-else Statements (cont.)  Better to over-use braces than under-use them – Can help to eliminate logic errors  Condition of an if statement must be a Boolean expression – Evaluates to true or false  A flowchart can be used to illustrate the behavior of if-else statements.
  • 16. Fundamentals of Java 16 The if and if-else Statements (cont.) Figure 4-1: Flowcharts for the if and if-else statements
  • 17. Fundamentals of Java 17 The if and if-else Statements (cont.)  Examples of if statements:
  • 18. Fundamentals of Java 18 The if and if-else Statements (cont.) Table 4-3: Relational operators
  • 19. Fundamentals of Java 19 The if and if-else Statements (cont.): Checking Input for Validity Example 4.1: Computes the area of a circle if the radius >= 0 or otherwise displays an error message
  • 20. Fundamentals of Java 20 The while Statement  Provides a looping mechanism – Executes statements repeatedly for as long as some condition remains true
  • 21. Fundamentals of Java 21 The while Statement (cont.) Figure 4-2: Flowchart for a while statement
  • 22. Fundamentals of Java 22 The while Statement (cont.)  Example:  Counter-controlled loop: – cntr is the counter – Loop repeats a determined number of times
  • 23. Fundamentals of Java 23 The while Statement (cont.)  Tracing: Track value of variables through each iteration of the loop Table 4-4: Trace of how variables change on each iteration through a loop
  • 24. Fundamentals of Java 24 The while Statement (cont.)  Counting backward:
  • 25. Fundamentals of Java 25 The while Statement (cont.)  Task-controlled loop: Continues to execute until some task is accomplished
  • 26. Fundamentals of Java 26 The while Statement (cont.)  Common structure of a while loop:
  • 27. Fundamentals of Java 27 The while Statement (cont.) Example 4.2: Compute and display the factorial of n
  • 28. Fundamentals of Java 28 The for statement  Combines counter initialization, condition test, and update into a single expression  Easy to create count-controlled loops
  • 29. Fundamentals of Java 29 The for statement (cont.)  Example:
  • 30. Fundamentals of Java 30 The for statement (cont.)  Count-controlled input:
  • 31. Fundamentals of Java 31 The for statement (cont.)  Better to declare the loop control variable within the loop header – Only visible within the loop – Variable name can be reused later in other loops
  • 32. Fundamentals of Java 32 The for statement (cont.)  Both for loops and while loops are entry- controlled loops. – Condition tested at top of loop on each pass  Choosing a for loop versus a while loop is often a matter of style. – for loop advantages: Can declare loop control variable in header Initialization, condition, and update in one line of code
  • 33. Fundamentals of Java 33 Nested Control Statements and the break Statement  Control statements may be nested.
  • 34. Fundamentals of Java 34 Nested Control Statements and the break Statement (cont.)  break statement: Prematurely end a loop
  • 35. Fundamentals of Java 35 Nested Control Statements and the break Statement (cont.)  Sentinel-controlled input: Continue a loop until a sentinel variable has a specific value
  • 36. Fundamentals of Java 36 Using Loops with Text Files  Advantages of using text files versus input from a human user: – Data sets can be much larger. – Data input quickly, with less chance of error. – Data can be used repeatedly.  Data files can be created by hand in a text editor or generated by a program.
  • 37. Fundamentals of Java 37 Using Loops with Text Files (cont.)  Text file format: – If data is numerical, numbers must be separated by white space. – Must be an end-of-file character Used by program to determine whether it is done reading data  When an error occurs at run-time, the JVM throws an exception. – IOException thrown if error occurs during file operations
  • 38. Fundamentals of Java 38 Using Loops with Text Files (cont.) Example 4.3: Computes and displays the average of a file of floating-point numbers
  • 39. Fundamentals of Java 39 Using Loops with Text Files (cont.) Example 4.4: Inputs a text file of integers and writes these to an output file without the zeroes
  • 40. Fundamentals of Java 40 Errors in Loops  May occur in initializing statements, terminating conditions, body statements, or update statements  Initialization error: Failure to initialize or initializes to incorrect value  Off-by-one error: Loop iterates one too many or one too few times
  • 41. Fundamentals of Java 41 Errors in Loops (cont.)  Infinite loop: Error in the terminating condition – Loop never terminates  Errors in loop body affect whether the loop completes its task correctly or at all.  Update error: Update statements in wrong place may affect calculations – Failing to update at all results in an infinite loop.
  • 42. Fundamentals of Java 42 Errors in Loops (cont.)  Effects of limited floating-point precision: When using floating-point variables as loop control variables, you must understand that not all values can be represented. – Better not to use == or != in condition statement under these conditions
  • 43. Fundamentals of Java 43 Errors in Loops (cont.)  Debugging loops: – If an error is suspected, make sure that: Variables are initialized before entering the loop The terminating condition stops the iterations when the test variables have reached the intended limit The statements in the body are correct
  • 44. Fundamentals of Java 44 Errors in Loops (cont.)  Debugging loops (cont.): – If an error is suspected, make sure that: The update statements are positioned correctly and modify the test variables so that they eventually pass the limits tested in the terminating condition
  • 45. Fundamentals of Java 45 Graphics and GUIs: I/O Dialog Boxes and Loops  A convenient way to accept input from a user is to pop up an input dialog box. – Use JOptionPane.showInputDialog(). Figure 4-4: Input dialog box
  • 46. Fundamentals of Java 46 Graphics and GUIs: I/O Dialog Boxes and Loops (cont.)  If expected input is a number, must use Integer.parseInt() or Double.parseDouble()  To output a message, use a message dialog box. – JOptionPane.showMessageDialog( anObserver, aString)
  • 47. Fundamentals of Java 47 Graphics and GUIs: I/O Dialog Boxes and Loops (cont.) Example 4.5: CircleArea with dialog I/O
  • 48. Fundamentals of Java 48 Graphics and GUIs: I/O Dialog Boxes and Loops (cont.) Figure 4.5: Dialog I/O user interface for the circle area program
  • 49. Fundamentals of Java 49 Graphics and GUIs: I/O Dialog Boxes and Loops (cont.)  Setting up multiple panels: – Can use a loop to initialize and install panels  Setting the preferred size of a panel: – Use JPanel class’s setPreferredSize() method. – JFrame class’s pack() method will cause the window to adjust its size to exactly fit the preferred size of any contained panels.
  • 50. Fundamentals of Java 50 Graphics and GUIs: I/O Dialog Boxes and Loops (cont.) Example 4-7: Color panel whose background is a color provided by the client. A client-specified preferred size is optional.
  • 51. Fundamentals of Java 51 Design, Testing, and Debugging Hints  Most errors involving selection statements and loops are not syntax errors.  The presence or absence of the {} symbols can seriously affect the logic of a selection statement or loop.  When testing programs that use if or if- else statements, use test data that forces the program to exercise all logical branches.
  • 52. Fundamentals of Java 52 Design, Testing, and Debugging Hints (cont.)  Use an if-else statement rather than two if statements when the alternative courses of action are mutually exclusive.  When testing a loop, be sure to use limit values as well as typical values.  Be sure to check entry conditions and exit conditions for each loop.
  • 53. Fundamentals of Java 53 Design, Testing, and Debugging Hints (cont.)  For a loop with errors, use debugging output statements to verify the values of the control variable on each pass through the loop.  Text files are convenient to use when the data set is large, when the same data set must be used repeatedly with different programs, and when these data must be saved permanently.
  • 54. Fundamentals of Java 54 Summary  Java has operators for extended assignment and for increment and decrement.  The Math class provides several useful methods, such as sqrt and abs.  The Random class allows you to generate random integers and floating-point numbers.  if and if-else statements are used to make one-way and two-way decisions.
  • 55. Fundamentals of Java 55 Summary (cont.)  The comparison operators, such as ==, <=, and >=, return Boolean values that can serve as conditions for control statements.  The while loop allows the program to run a set of statements repeatedly until a condition becomes false.  The for loop is a more concise version of the while loop.
  • 56. Fundamentals of Java 56 Summary (cont.)  Other control statements, such as an if statement, can be nested within loops.  A break statement can be used with an if statement to terminate a loop early.  Many kinds of logic errors can occur in loops. – Off-by-one error – Infinite loop