SlideShare a Scribd company logo
Java Programming, 3e
Concepts and Techniques
Chapter 4
Decision Making and
Repetition with
Reusable Objects
2Chapter 4: Decision Making and Repetition with Reusable Objects
Chapter Objectives
• Design a program using methods
• Code a selection structure to make
decisions in code
• Describe the use of the logical AND, OR,
and NOT operators
• Define exceptions and exception handling
3Chapter 4: Decision Making and Repetition with Reusable Objects
Chapter Objectives
• Code a try statement and a catch
statement to handle exceptions
• Create a user-defined method
• Code a repetition structure using the while
statement
• Write a switch statement to test for
multiple values in data
4Chapter 4: Decision Making and Repetition with Reusable Objects
Chapter Objectives
• Format numbers using a pattern and the
format() method
• Construct a Color object
• Use a Checkbox and a CheckboxGroup in
the user interface
5Chapter 4: Decision Making and Repetition with Reusable Objects
Introduction
• Control structures alter the sequential
execution of code
– Selection structure
– Repetition structure
• User-defined methods break tasks into
reusable sections of code
• Exception handling in Java allows for the
testing of valid and accurate input
6Chapter 4: Decision Making and Repetition with Reusable Objects
The Sales Commission Program
• Calculate sales commission for agents in a
travel agency
• Coded as a console application and an applet
• Input
– The user chooses from three types of commission
codes
• The commission code identifies the type of sale and the
commission rate
– The user enters a sales amount
• Calculate commission and display output
7Chapter 4: Decision Making and Repetition with Reusable Objects
8Chapter 4: Decision Making and Repetition with Reusable Objects
Program Development
• Problem analysis
– Each user decision corresponds to a program task
– Develop and test each task before adding it to the
program
• Design the solution
– Design storyboards for the two user interfaces
• Program design
– Design a flowchart consisting of required methods
– Write related pseudocode for each method
• Validate Design
9Chapter 4: Decision Making and Repetition with Reusable Objects
10Chapter 4: Decision Making and Repetition with Reusable Objects
Coding the Program
• Code the program using program stubs
– Stubs are incomplete portions of code that serve as a
template or placeholder for later code
– Stubs allow ease in debugging through incremental
compilation and testing
• Import java.swing.JOptionPane
• Import java.text.DecimalFormat
– Formats decimal output into Strings
• Declare variables
• Compile and test the program stub
11Chapter 4: Decision Making and Repetition with Reusable Objects
Coding the Program
12Chapter 4: Decision Making and Repetition with Reusable Objects
Writing Methods
• A program with modules allows for clarity,
reusability, and refinement
• The code for each module can be separated into
programmer-defined methods
• The main() method transfers execution to the
methods through a call statement
• The called method returns control to its caller
with the return statement or the ending brace
– The return statement returns any required data back
to the calling method
13Chapter 4: Decision Making and Repetition with Reusable Objects
14Chapter 4: Decision Making and Repetition with Reusable Objects
The if…else Statement
• Single: line 30, line 31
• Block: lines 15-27, lines 19-20, lines 24-25
• Nested: lines 17-26, lines 30-31
15Chapter 4: Decision Making and Repetition with Reusable Objects
16Chapter 4: Decision Making and Repetition with Reusable Objects
Testing with an if statement
• Testing a single condition
– if (answer == null)
– if (!done)
• Testing multiple conditions
– if ((gender == “male”) && (age >= 18))
– if ((age < 13) || (age > 65))
– AND and OR expressions evaluate the right
operand only if the left operand is not
sufficient to decide the condition
17Chapter 4: Decision Making and Repetition with Reusable Objects
Exception Handling
• An exception is an event resulting from an
erroneous situation which disrupts normal
program flow
• Exception handling is the concept of planning for
possible exceptions by directing the program to
deal with them gracefully, without terminating
• Three kinds of exceptions
– I/O
– Run-time
– Checked
• The compiler checks each method to ensure each method
has a handler
18Chapter 4: Decision Making and Repetition with Reusable Objects
Handling Exceptions
• The try statement identifies a block of statements that
may potentially throw an exception
• The throw statement transfers execution from the
method that caused the exception to the handler
– Transfers execution to the catch statement if the throw is placed
within a try statement
• The catch statement identifies the type of exception
being caught and statements to describe or fix the error
• The finally statement is optional and is always executed
regardless of whether an exception has taken place
– Placed after the catch statement
19Chapter 4: Decision Making and Repetition with Reusable Objects
20Chapter 4: Decision Making and Repetition with Reusable Objects
21Chapter 4: Decision Making and Repetition with Reusable Objects
Catch an exception
Throw an exception
22Chapter 4: Decision Making and Repetition with Reusable Objects
Throwing an Exception
• Compile the program after coding each method
and call statement
• Run the program with correct input
• Run the program to test the exception handling
with invalid input
– Alphabetic data
– Negative values
– Null or zero values
• Verify that the user is allowed to reenter data
• Verify the program closes correctly
23Chapter 4: Decision Making and Repetition with Reusable Objects
Repetition Structure
24Chapter 4: Decision Making and Repetition with Reusable Objects
The getSales() method
25Chapter 4: Decision Making and Repetition with Reusable Objects
The getCode() method
26Chapter 4: Decision Making and Repetition with Reusable Objects
The Case Structure
• A type of selection structure that allows for more
than two choices when the condition is
evaluated
• Used when there are many possible, valid
choices for user input
• The code evaluates the user choice with a
switch statement and looks for a match in each
case statement
• Each case statement contains a ending break
statement which forces exit of the structure
27Chapter 4: Decision Making and Repetition with Reusable Objects
28Chapter 4: Decision Making and Repetition with Reusable Objects
The getComm() Method
29Chapter 4: Decision Making and Repetition with Reusable Objects
Arguments and Parameters
• When a method is called, the calling method
sends arguments; the called method accepts the
values as parameters
• Different but related identifier names for the
arguments and the parameters should be used
for good program design
– The variables are only visible in their respective
methods
• Arguments and parameters for a called method
and the calling statement must be of the same
number, order, and data type
30Chapter 4: Decision Making and Repetition with Reusable Objects
Formatting Numeric Output
• The DecimalFormat class formats decimal numbers into Strings for
output
• Supports different locales, leading and trailing zeros,
prefixes/suffixes, and separators
• The argument is a pattern, which determines how the formatted
number should be displayed
31Chapter 4: Decision Making and Repetition with Reusable Objects
32Chapter 4: Decision Making and Repetition with Reusable Objects
The output() method
33Chapter 4: Decision Making and Repetition with Reusable Objects
The finish() method
Exits system when program completes successfully
34Chapter 4: Decision Making and Repetition with Reusable Objects
Moving to the Web
• Create the host document to execute the applet
35Chapter 4: Decision Making and Repetition with Reusable Objects
Coding an Applet Stub
• Enter general block comments
• Import java.awt.*, java.applet.*, java.awt.event.*,
and java.text.DecimalFormat
• Implement the ItemListener interface to listen for
the user choice on a Checkbox
• Code the method headers for the init() and the
itemStateChanged() method
– itemStateChanged() is an ItemListener method to
process user choices
• Declare variables and construct a Color object
36Chapter 4: Decision Making and Repetition with Reusable Objects
37Chapter 4: Decision Making and Repetition with Reusable Objects
Making Decisions in Applets
• Use a CheckboxGroup to allow user choices
38Chapter 4: Decision Making and Repetition with Reusable Objects
Constructing Applet Components
• Construct Labels for input and output
• Construct a CheckboxGroup for user options
39Chapter 4: Decision Making and Repetition with Reusable Objects
Constructing Applet Components
• Add Labels and CheckboxGroup to the
applet
• Add an ItemListener to each Checkbox
component with the addItemListener()
method
• Add color with the setForeground() and
the setBackground() methods
• Set the insertion point with the
requestFocus() method
40Chapter 4: Decision Making and Repetition with Reusable Objects
The init() Method
41Chapter 4: Decision Making and Repetition with Reusable Objects
Handling Exceptions
• Check for valid data when the itemStateChanged()
method is triggered, which happens when the user clicks
an option button
42Chapter 4: Decision Making and Repetition with Reusable Objects
The getSales() Method
• Parse the data from the TextField and return a valid
sales amount or throw an exception to the init() method
43Chapter 4: Decision Making and Repetition with Reusable Objects
The getCode() Method
• Initialize the code to 0
• Use nested if statements to assess the boolean state of
the Checkboxes and return the code to init()
44Chapter 4: Decision Making and Repetition with Reusable Objects
The getComm() Method
• Identical to the application
• Return the commission value to init()
45Chapter 4: Decision Making and Repetition with Reusable Objects
The output() Method
• Send output to the Label using setText()
• Construct and use DecimalFormat, using the special
character # to make a leading zero absent
46Chapter 4: Decision Making and Repetition with Reusable Objects
The paint() Method
• Display a graphic
47Chapter 4: Decision Making and Repetition with Reusable Objects
Compiling and Testing the Applet
• Compile the applet
• Execute the applet using AppletViewer
• Test exception handling by clicking an option button and
then typing invalid data into the text box
• Verify the error message and the data clearing
mechanisms
• Test all options with valid data
• Test in a browser window
• Document the applet interface and source code
48Chapter 4: Decision Making and Repetition with Reusable Objects
Chapter Summary
• Design a program using methods
• Code a selection structure to make
decisions in code
• Describe the use of the logical AND, OR,
and NOT operators
• Define exceptions and exception handling
49Chapter 4: Decision Making and Repetition with Reusable Objects
Chapter Summary
• Code a try statement and a catch
statement to handle exceptions
• Create a user-defined method
• Code a repetition structure using the while
statement
• Write a switch statement to test for
multiple values in data
50Chapter 4: Decision Making and Repetition with Reusable Objects
Chapter Summary
• Format numbers using a pattern and the
format() method
• Construct a Color object
• Use a Checkbox and a CheckboxGroup in
the user interface
Java Programming, 3e
Concepts and Techniques
Chapter 4 Complete

More Related Content

What's hot

CIS110 Computer Programming Design Chapter (10)
CIS110 Computer Programming Design Chapter  (10)CIS110 Computer Programming Design Chapter  (10)
CIS110 Computer Programming Design Chapter (10)
Dr. Ahmed Al Zaidy
 
Programming Logic and Design: Working with Data
Programming Logic and Design: Working with DataProgramming Logic and Design: Working with Data
Programming Logic and Design: Working with Data
Nicole Ryan
 
CIS110 Computer Programming Design Chapter (6)
CIS110 Computer Programming Design Chapter  (6)CIS110 Computer Programming Design Chapter  (6)
CIS110 Computer Programming Design Chapter (6)
Dr. Ahmed Al Zaidy
 
Course Breakup Plan- C
Course Breakup Plan- CCourse Breakup Plan- C
Course Breakup Plan- C
swatisinghal
 
MATLAB Basics-Part1
MATLAB Basics-Part1MATLAB Basics-Part1
MATLAB Basics-Part1
Elaf A.Saeed
 
Prelim Project OOP
Prelim Project OOPPrelim Project OOP
Prelim Project OOP
Dwight Sabio
 
Taking your machine learning workflow to the next level using Scikit-Learn Pi...
Taking your machine learning workflow to the next level using Scikit-Learn Pi...Taking your machine learning workflow to the next level using Scikit-Learn Pi...
Taking your machine learning workflow to the next level using Scikit-Learn Pi...
Philip Goddard
 
9781285852744 ppt ch08
9781285852744 ppt ch089781285852744 ppt ch08
9781285852744 ppt ch08
Terry Yoast
 
Intake 38 3
Intake 38 3Intake 38 3
Intake 38 3
Mahmoud Ouf
 
Array sorting
Array sortingArray sorting
Array sorting
ALI RAZA
 
Intake 38 4
Intake 38 4Intake 38 4
Intake 38 4
Mahmoud Ouf
 
Stack&heap
Stack&heapStack&heap
Intro to Programming: Modularity
Intro to Programming: ModularityIntro to Programming: Modularity
Intro to Programming: Modularity
Nicole Ryan
 
Results for EvoSuite-MOSA at the Third Unit Testing Tool Competition
Results for EvoSuite-MOSA at the Third Unit Testing Tool CompetitionResults for EvoSuite-MOSA at the Third Unit Testing Tool Competition
Results for EvoSuite-MOSA at the Third Unit Testing Tool Competition
Annibale Panichella
 
Introduction to matlab
Introduction to matlabIntroduction to matlab
Introduction to matlab
vikrammutneja1
 
Presentation 1st
Presentation 1stPresentation 1st
Presentation 1st
Connex
 
C Programming : Pointers and Strings
C Programming : Pointers and StringsC Programming : Pointers and Strings
C Programming : Pointers and Strings
Selvaraj Seerangan
 
Implicit and explicit sequence control with exception handling
Implicit and explicit sequence control with exception handlingImplicit and explicit sequence control with exception handling
Implicit and explicit sequence control with exception handling
VIKASH MAINANWAL
 

What's hot (18)

CIS110 Computer Programming Design Chapter (10)
CIS110 Computer Programming Design Chapter  (10)CIS110 Computer Programming Design Chapter  (10)
CIS110 Computer Programming Design Chapter (10)
 
Programming Logic and Design: Working with Data
Programming Logic and Design: Working with DataProgramming Logic and Design: Working with Data
Programming Logic and Design: Working with Data
 
CIS110 Computer Programming Design Chapter (6)
CIS110 Computer Programming Design Chapter  (6)CIS110 Computer Programming Design Chapter  (6)
CIS110 Computer Programming Design Chapter (6)
 
Course Breakup Plan- C
Course Breakup Plan- CCourse Breakup Plan- C
Course Breakup Plan- C
 
MATLAB Basics-Part1
MATLAB Basics-Part1MATLAB Basics-Part1
MATLAB Basics-Part1
 
Prelim Project OOP
Prelim Project OOPPrelim Project OOP
Prelim Project OOP
 
Taking your machine learning workflow to the next level using Scikit-Learn Pi...
Taking your machine learning workflow to the next level using Scikit-Learn Pi...Taking your machine learning workflow to the next level using Scikit-Learn Pi...
Taking your machine learning workflow to the next level using Scikit-Learn Pi...
 
9781285852744 ppt ch08
9781285852744 ppt ch089781285852744 ppt ch08
9781285852744 ppt ch08
 
Intake 38 3
Intake 38 3Intake 38 3
Intake 38 3
 
Array sorting
Array sortingArray sorting
Array sorting
 
Intake 38 4
Intake 38 4Intake 38 4
Intake 38 4
 
Stack&heap
Stack&heapStack&heap
Stack&heap
 
Intro to Programming: Modularity
Intro to Programming: ModularityIntro to Programming: Modularity
Intro to Programming: Modularity
 
Results for EvoSuite-MOSA at the Third Unit Testing Tool Competition
Results for EvoSuite-MOSA at the Third Unit Testing Tool CompetitionResults for EvoSuite-MOSA at the Third Unit Testing Tool Competition
Results for EvoSuite-MOSA at the Third Unit Testing Tool Competition
 
Introduction to matlab
Introduction to matlabIntroduction to matlab
Introduction to matlab
 
Presentation 1st
Presentation 1stPresentation 1st
Presentation 1st
 
C Programming : Pointers and Strings
C Programming : Pointers and StringsC Programming : Pointers and Strings
C Programming : Pointers and Strings
 
Implicit and explicit sequence control with exception handling
Implicit and explicit sequence control with exception handlingImplicit and explicit sequence control with exception handling
Implicit and explicit sequence control with exception handling
 

Viewers also liked

Target markets
Target marketsTarget markets
Target markets
Chaffey College
 
Passing data in cgi
Passing data in cgiPassing data in cgi
Passing data in cgi
Chaffey College
 
The games factory 2 alien wars
The games factory 2 alien warsThe games factory 2 alien wars
The games factory 2 alien wars
Chaffey College
 
Social networks and games
Social networks and gamesSocial networks and games
Social networks and games
Chaffey College
 
Puzzle design
Puzzle designPuzzle design
Puzzle design
Chaffey College
 
Ch 1 alice
Ch 1 aliceCh 1 alice
Ch 1 alice
Chaffey College
 

Viewers also liked (6)

Target markets
Target marketsTarget markets
Target markets
 
Passing data in cgi
Passing data in cgiPassing data in cgi
Passing data in cgi
 
The games factory 2 alien wars
The games factory 2 alien warsThe games factory 2 alien wars
The games factory 2 alien wars
 
Social networks and games
Social networks and gamesSocial networks and games
Social networks and games
 
Puzzle design
Puzzle designPuzzle design
Puzzle design
 
Ch 1 alice
Ch 1 aliceCh 1 alice
Ch 1 alice
 

Similar to Chapter 04

COMPILER DESIGN Run-Time Environments
COMPILER DESIGN Run-Time EnvironmentsCOMPILER DESIGN Run-Time Environments
Java Unit Testing Tool Competition — Fifth Round
Java Unit Testing Tool Competition — Fifth RoundJava Unit Testing Tool Competition — Fifth Round
Java Unit Testing Tool Competition — Fifth Round
Annibale Panichella
 
CIS110 Computer Programming Design Chapter (9)
CIS110 Computer Programming Design Chapter  (9)CIS110 Computer Programming Design Chapter  (9)
CIS110 Computer Programming Design Chapter (9)
Dr. Ahmed Al Zaidy
 
Constructors and Method Overloading
Constructors and Method OverloadingConstructors and Method Overloading
Constructors and Method Overloading
Ferdin Joe John Joseph PhD
 
functions (1).pptx
functions (1).pptxfunctions (1).pptx
functions (1).pptx
ssuser47f7f2
 
QBA Simulation and Inventory.pptx
QBA Simulation and Inventory.pptxQBA Simulation and Inventory.pptx
QBA Simulation and Inventory.pptx
ArthurRanola
 
Csc153 chapter 07
Csc153 chapter 07Csc153 chapter 07
Csc153 chapter 07
PCC
 
Java 102 intro to object-oriented programming in java
Java 102   intro to object-oriented programming in javaJava 102   intro to object-oriented programming in java
Java 102 intro to object-oriented programming in java
agorolabs
 
Code and Design Smells. Are They a Real Threat?
Code and Design Smells. Are They a Real Threat?Code and Design Smells. Are They a Real Threat?
Code and Design Smells. Are They a Real Threat?
GlobalLogic Ukraine
 
Section1 compound data class
Section1 compound data classSection1 compound data class
Section1 compound data class
Dương Tùng
 
Practical model management in the age of Data science and ML
Practical model management in the age of Data science and MLPractical model management in the age of Data science and ML
Practical model management in the age of Data science and ML
QuantUniversity
 
CIS 1403 lab 3 functions and methods in Java
CIS 1403 lab 3 functions and methods in JavaCIS 1403 lab 3 functions and methods in Java
CIS 1403 lab 3 functions and methods in Java
Hamad Odhabi
 
Software metrics by Dr. B. J. Mohite
Software metrics by Dr. B. J. MohiteSoftware metrics by Dr. B. J. Mohite
Software metrics by Dr. B. J. Mohite
Zeal Education Society, Pune
 
Experimental Design for Distributed Machine Learning with Myles Baker
Experimental Design for Distributed Machine Learning with Myles BakerExperimental Design for Distributed Machine Learning with Myles Baker
Experimental Design for Distributed Machine Learning with Myles Baker
Databricks
 
NDepend Public PPT (2008)
NDepend Public PPT (2008)NDepend Public PPT (2008)
NDepend Public PPT (2008)
NDepend
 
IT8076 - SOFTWARE TESTING
IT8076 - SOFTWARE TESTINGIT8076 - SOFTWARE TESTING
IT8076 - SOFTWARE TESTING
Sathya R
 
Unit 2 - Test Case Design
Unit 2 - Test Case DesignUnit 2 - Test Case Design
Unit 2 - Test Case Design
Selvi Vts
 
20150814 Wrangling Data From Raw to Tidy vs
20150814 Wrangling Data From Raw to Tidy vs20150814 Wrangling Data From Raw to Tidy vs
20150814 Wrangling Data From Raw to Tidy vs
Ian Feller
 
Web_Intelligence_Activity_Workbook_Sample
Web_Intelligence_Activity_Workbook_SampleWeb_Intelligence_Activity_Workbook_Sample
Web_Intelligence_Activity_Workbook_Sample
Ronald Ciampi
 
Java 102
Java 102Java 102
Java 102
Manuela Grindei
 

Similar to Chapter 04 (20)

COMPILER DESIGN Run-Time Environments
COMPILER DESIGN Run-Time EnvironmentsCOMPILER DESIGN Run-Time Environments
COMPILER DESIGN Run-Time Environments
 
Java Unit Testing Tool Competition — Fifth Round
Java Unit Testing Tool Competition — Fifth RoundJava Unit Testing Tool Competition — Fifth Round
Java Unit Testing Tool Competition — Fifth Round
 
CIS110 Computer Programming Design Chapter (9)
CIS110 Computer Programming Design Chapter  (9)CIS110 Computer Programming Design Chapter  (9)
CIS110 Computer Programming Design Chapter (9)
 
Constructors and Method Overloading
Constructors and Method OverloadingConstructors and Method Overloading
Constructors and Method Overloading
 
functions (1).pptx
functions (1).pptxfunctions (1).pptx
functions (1).pptx
 
QBA Simulation and Inventory.pptx
QBA Simulation and Inventory.pptxQBA Simulation and Inventory.pptx
QBA Simulation and Inventory.pptx
 
Csc153 chapter 07
Csc153 chapter 07Csc153 chapter 07
Csc153 chapter 07
 
Java 102 intro to object-oriented programming in java
Java 102   intro to object-oriented programming in javaJava 102   intro to object-oriented programming in java
Java 102 intro to object-oriented programming in java
 
Code and Design Smells. Are They a Real Threat?
Code and Design Smells. Are They a Real Threat?Code and Design Smells. Are They a Real Threat?
Code and Design Smells. Are They a Real Threat?
 
Section1 compound data class
Section1 compound data classSection1 compound data class
Section1 compound data class
 
Practical model management in the age of Data science and ML
Practical model management in the age of Data science and MLPractical model management in the age of Data science and ML
Practical model management in the age of Data science and ML
 
CIS 1403 lab 3 functions and methods in Java
CIS 1403 lab 3 functions and methods in JavaCIS 1403 lab 3 functions and methods in Java
CIS 1403 lab 3 functions and methods in Java
 
Software metrics by Dr. B. J. Mohite
Software metrics by Dr. B. J. MohiteSoftware metrics by Dr. B. J. Mohite
Software metrics by Dr. B. J. Mohite
 
Experimental Design for Distributed Machine Learning with Myles Baker
Experimental Design for Distributed Machine Learning with Myles BakerExperimental Design for Distributed Machine Learning with Myles Baker
Experimental Design for Distributed Machine Learning with Myles Baker
 
NDepend Public PPT (2008)
NDepend Public PPT (2008)NDepend Public PPT (2008)
NDepend Public PPT (2008)
 
IT8076 - SOFTWARE TESTING
IT8076 - SOFTWARE TESTINGIT8076 - SOFTWARE TESTING
IT8076 - SOFTWARE TESTING
 
Unit 2 - Test Case Design
Unit 2 - Test Case DesignUnit 2 - Test Case Design
Unit 2 - Test Case Design
 
20150814 Wrangling Data From Raw to Tidy vs
20150814 Wrangling Data From Raw to Tidy vs20150814 Wrangling Data From Raw to Tidy vs
20150814 Wrangling Data From Raw to Tidy vs
 
Web_Intelligence_Activity_Workbook_Sample
Web_Intelligence_Activity_Workbook_SampleWeb_Intelligence_Activity_Workbook_Sample
Web_Intelligence_Activity_Workbook_Sample
 
Java 102
Java 102Java 102
Java 102
 

More from Chaffey College

Strings Objects Variables
Strings Objects VariablesStrings Objects Variables
Strings Objects Variables
Chaffey College
 
Ruby Chapter 2
Ruby Chapter 2Ruby Chapter 2
Ruby Chapter 2
Chaffey College
 
Serious games
Serious gamesSerious games
Serious games
Chaffey College
 
Ch 8 introduction to data structures
Ch 8 introduction to data structuresCh 8 introduction to data structures
Ch 8 introduction to data structures
Chaffey College
 
Ch 8 data structures in alice
Ch 8  data structures in aliceCh 8  data structures in alice
Ch 8 data structures in alice
Chaffey College
 
Ch 7 recursion
Ch 7 recursionCh 7 recursion
Ch 7 recursion
Chaffey College
 
Intro to gml
Intro to gmlIntro to gml
Intro to gml
Chaffey College
 
Power point unit d
Power point unit dPower point unit d
Power point unit d
Chaffey College
 
Power point unit c
Power point unit cPower point unit c
Power point unit c
Chaffey College
 
Power point unit b
Power point unit bPower point unit b
Power point unit b
Chaffey College
 
Power point unit a
Power point unit aPower point unit a
Power point unit a
Chaffey College
 
Gamegraphics
GamegraphicsGamegraphics
Gamegraphics
Chaffey College
 
Gamesound
GamesoundGamesound
Gamesound
Chaffey College
 
Ch 6 text and sound in alice
Ch 6 text and sound in aliceCh 6 text and sound in alice
Ch 6 text and sound in alice
Chaffey College
 
Ch 5 boolean logic
Ch 5 boolean logicCh 5 boolean logic
Ch 5 boolean logic
Chaffey College
 
Ch 5 boolean logical in alice
Ch 5  boolean logical in aliceCh 5  boolean logical in alice
Ch 5 boolean logical in alice
Chaffey College
 
Game maker objects
Game maker objectsGame maker objects
Game maker objects
Chaffey College
 
Ch 3 event driven programming
Ch 3 event driven programmingCh 3 event driven programming
Ch 3 event driven programming
Chaffey College
 
Ch 4 structure of algorithms
Ch 4 structure of algorithmsCh 4 structure of algorithms
Ch 4 structure of algorithms
Chaffey College
 
Ch 5 boolean logic
Ch 5 boolean logicCh 5 boolean logic
Ch 5 boolean logic
Chaffey College
 

More from Chaffey College (20)

Strings Objects Variables
Strings Objects VariablesStrings Objects Variables
Strings Objects Variables
 
Ruby Chapter 2
Ruby Chapter 2Ruby Chapter 2
Ruby Chapter 2
 
Serious games
Serious gamesSerious games
Serious games
 
Ch 8 introduction to data structures
Ch 8 introduction to data structuresCh 8 introduction to data structures
Ch 8 introduction to data structures
 
Ch 8 data structures in alice
Ch 8  data structures in aliceCh 8  data structures in alice
Ch 8 data structures in alice
 
Ch 7 recursion
Ch 7 recursionCh 7 recursion
Ch 7 recursion
 
Intro to gml
Intro to gmlIntro to gml
Intro to gml
 
Power point unit d
Power point unit dPower point unit d
Power point unit d
 
Power point unit c
Power point unit cPower point unit c
Power point unit c
 
Power point unit b
Power point unit bPower point unit b
Power point unit b
 
Power point unit a
Power point unit aPower point unit a
Power point unit a
 
Gamegraphics
GamegraphicsGamegraphics
Gamegraphics
 
Gamesound
GamesoundGamesound
Gamesound
 
Ch 6 text and sound in alice
Ch 6 text and sound in aliceCh 6 text and sound in alice
Ch 6 text and sound in alice
 
Ch 5 boolean logic
Ch 5 boolean logicCh 5 boolean logic
Ch 5 boolean logic
 
Ch 5 boolean logical in alice
Ch 5  boolean logical in aliceCh 5  boolean logical in alice
Ch 5 boolean logical in alice
 
Game maker objects
Game maker objectsGame maker objects
Game maker objects
 
Ch 3 event driven programming
Ch 3 event driven programmingCh 3 event driven programming
Ch 3 event driven programming
 
Ch 4 structure of algorithms
Ch 4 structure of algorithmsCh 4 structure of algorithms
Ch 4 structure of algorithms
 
Ch 5 boolean logic
Ch 5 boolean logicCh 5 boolean logic
Ch 5 boolean logic
 

Recently uploaded

Generating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and MilvusGenerating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and Milvus
Zilliz
 
HCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAUHCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAU
panagenda
 
Skybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoptionSkybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoption
Tatiana Kojar
 
What is an RPA CoE? Session 1 – CoE Vision
What is an RPA CoE?  Session 1 – CoE VisionWhat is an RPA CoE?  Session 1 – CoE Vision
What is an RPA CoE? Session 1 – CoE Vision
DianaGray10
 
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdfHow to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
Chart Kalyan
 
9 CEO's who hit $100m ARR Share Their Top Growth Tactics Nathan Latka, Founde...
9 CEO's who hit $100m ARR Share Their Top Growth Tactics Nathan Latka, Founde...9 CEO's who hit $100m ARR Share Their Top Growth Tactics Nathan Latka, Founde...
9 CEO's who hit $100m ARR Share Their Top Growth Tactics Nathan Latka, Founde...
saastr
 
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdfMonitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Tosin Akinosho
 
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success StoryDriving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Safe Software
 
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-EfficiencyFreshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
ScyllaDB
 
Essentials of Automations: Exploring Attributes & Automation Parameters
Essentials of Automations: Exploring Attributes & Automation ParametersEssentials of Automations: Exploring Attributes & Automation Parameters
Essentials of Automations: Exploring Attributes & Automation Parameters
Safe Software
 
Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024
Jason Packer
 
Nordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptxNordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptx
MichaelKnudsen27
 
Introduction of Cybersecurity with OSS at Code Europe 2024
Introduction of Cybersecurity with OSS  at Code Europe 2024Introduction of Cybersecurity with OSS  at Code Europe 2024
Introduction of Cybersecurity with OSS at Code Europe 2024
Hiroshi SHIBATA
 
Principle of conventional tomography-Bibash Shahi ppt..pptx
Principle of conventional tomography-Bibash Shahi ppt..pptxPrinciple of conventional tomography-Bibash Shahi ppt..pptx
Principle of conventional tomography-Bibash Shahi ppt..pptx
BibashShahi
 
Dandelion Hashtable: beyond billion requests per second on a commodity server
Dandelion Hashtable: beyond billion requests per second on a commodity serverDandelion Hashtable: beyond billion requests per second on a commodity server
Dandelion Hashtable: beyond billion requests per second on a commodity server
Antonios Katsarakis
 
GraphRAG for LifeSciences Hands-On with the Clinical Knowledge Graph
GraphRAG for LifeSciences Hands-On with the Clinical Knowledge GraphGraphRAG for LifeSciences Hands-On with the Clinical Knowledge Graph
GraphRAG for LifeSciences Hands-On with the Clinical Knowledge Graph
Neo4j
 
Fueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte WebinarFueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte Webinar
Zilliz
 
Y-Combinator seed pitch deck template PP
Y-Combinator seed pitch deck template PPY-Combinator seed pitch deck template PP
Y-Combinator seed pitch deck template PP
c5vrf27qcz
 
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
Alex Pruden
 

Recently uploaded (20)

Generating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and MilvusGenerating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and Milvus
 
Artificial Intelligence and Electronic Warfare
Artificial Intelligence and Electronic WarfareArtificial Intelligence and Electronic Warfare
Artificial Intelligence and Electronic Warfare
 
HCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAUHCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAU
 
Skybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoptionSkybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoption
 
What is an RPA CoE? Session 1 – CoE Vision
What is an RPA CoE?  Session 1 – CoE VisionWhat is an RPA CoE?  Session 1 – CoE Vision
What is an RPA CoE? Session 1 – CoE Vision
 
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdfHow to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
 
9 CEO's who hit $100m ARR Share Their Top Growth Tactics Nathan Latka, Founde...
9 CEO's who hit $100m ARR Share Their Top Growth Tactics Nathan Latka, Founde...9 CEO's who hit $100m ARR Share Their Top Growth Tactics Nathan Latka, Founde...
9 CEO's who hit $100m ARR Share Their Top Growth Tactics Nathan Latka, Founde...
 
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdfMonitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdf
 
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success StoryDriving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success Story
 
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-EfficiencyFreshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
 
Essentials of Automations: Exploring Attributes & Automation Parameters
Essentials of Automations: Exploring Attributes & Automation ParametersEssentials of Automations: Exploring Attributes & Automation Parameters
Essentials of Automations: Exploring Attributes & Automation Parameters
 
Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024
 
Nordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptxNordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptx
 
Introduction of Cybersecurity with OSS at Code Europe 2024
Introduction of Cybersecurity with OSS  at Code Europe 2024Introduction of Cybersecurity with OSS  at Code Europe 2024
Introduction of Cybersecurity with OSS at Code Europe 2024
 
Principle of conventional tomography-Bibash Shahi ppt..pptx
Principle of conventional tomography-Bibash Shahi ppt..pptxPrinciple of conventional tomography-Bibash Shahi ppt..pptx
Principle of conventional tomography-Bibash Shahi ppt..pptx
 
Dandelion Hashtable: beyond billion requests per second on a commodity server
Dandelion Hashtable: beyond billion requests per second on a commodity serverDandelion Hashtable: beyond billion requests per second on a commodity server
Dandelion Hashtable: beyond billion requests per second on a commodity server
 
GraphRAG for LifeSciences Hands-On with the Clinical Knowledge Graph
GraphRAG for LifeSciences Hands-On with the Clinical Knowledge GraphGraphRAG for LifeSciences Hands-On with the Clinical Knowledge Graph
GraphRAG for LifeSciences Hands-On with the Clinical Knowledge Graph
 
Fueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte WebinarFueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte Webinar
 
Y-Combinator seed pitch deck template PP
Y-Combinator seed pitch deck template PPY-Combinator seed pitch deck template PP
Y-Combinator seed pitch deck template PP
 
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
 

Chapter 04

  • 1. Java Programming, 3e Concepts and Techniques Chapter 4 Decision Making and Repetition with Reusable Objects
  • 2. 2Chapter 4: Decision Making and Repetition with Reusable Objects Chapter Objectives • Design a program using methods • Code a selection structure to make decisions in code • Describe the use of the logical AND, OR, and NOT operators • Define exceptions and exception handling
  • 3. 3Chapter 4: Decision Making and Repetition with Reusable Objects Chapter Objectives • Code a try statement and a catch statement to handle exceptions • Create a user-defined method • Code a repetition structure using the while statement • Write a switch statement to test for multiple values in data
  • 4. 4Chapter 4: Decision Making and Repetition with Reusable Objects Chapter Objectives • Format numbers using a pattern and the format() method • Construct a Color object • Use a Checkbox and a CheckboxGroup in the user interface
  • 5. 5Chapter 4: Decision Making and Repetition with Reusable Objects Introduction • Control structures alter the sequential execution of code – Selection structure – Repetition structure • User-defined methods break tasks into reusable sections of code • Exception handling in Java allows for the testing of valid and accurate input
  • 6. 6Chapter 4: Decision Making and Repetition with Reusable Objects The Sales Commission Program • Calculate sales commission for agents in a travel agency • Coded as a console application and an applet • Input – The user chooses from three types of commission codes • The commission code identifies the type of sale and the commission rate – The user enters a sales amount • Calculate commission and display output
  • 7. 7Chapter 4: Decision Making and Repetition with Reusable Objects
  • 8. 8Chapter 4: Decision Making and Repetition with Reusable Objects Program Development • Problem analysis – Each user decision corresponds to a program task – Develop and test each task before adding it to the program • Design the solution – Design storyboards for the two user interfaces • Program design – Design a flowchart consisting of required methods – Write related pseudocode for each method • Validate Design
  • 9. 9Chapter 4: Decision Making and Repetition with Reusable Objects
  • 10. 10Chapter 4: Decision Making and Repetition with Reusable Objects Coding the Program • Code the program using program stubs – Stubs are incomplete portions of code that serve as a template or placeholder for later code – Stubs allow ease in debugging through incremental compilation and testing • Import java.swing.JOptionPane • Import java.text.DecimalFormat – Formats decimal output into Strings • Declare variables • Compile and test the program stub
  • 11. 11Chapter 4: Decision Making and Repetition with Reusable Objects Coding the Program
  • 12. 12Chapter 4: Decision Making and Repetition with Reusable Objects Writing Methods • A program with modules allows for clarity, reusability, and refinement • The code for each module can be separated into programmer-defined methods • The main() method transfers execution to the methods through a call statement • The called method returns control to its caller with the return statement or the ending brace – The return statement returns any required data back to the calling method
  • 13. 13Chapter 4: Decision Making and Repetition with Reusable Objects
  • 14. 14Chapter 4: Decision Making and Repetition with Reusable Objects The if…else Statement • Single: line 30, line 31 • Block: lines 15-27, lines 19-20, lines 24-25 • Nested: lines 17-26, lines 30-31
  • 15. 15Chapter 4: Decision Making and Repetition with Reusable Objects
  • 16. 16Chapter 4: Decision Making and Repetition with Reusable Objects Testing with an if statement • Testing a single condition – if (answer == null) – if (!done) • Testing multiple conditions – if ((gender == “male”) && (age >= 18)) – if ((age < 13) || (age > 65)) – AND and OR expressions evaluate the right operand only if the left operand is not sufficient to decide the condition
  • 17. 17Chapter 4: Decision Making and Repetition with Reusable Objects Exception Handling • An exception is an event resulting from an erroneous situation which disrupts normal program flow • Exception handling is the concept of planning for possible exceptions by directing the program to deal with them gracefully, without terminating • Three kinds of exceptions – I/O – Run-time – Checked • The compiler checks each method to ensure each method has a handler
  • 18. 18Chapter 4: Decision Making and Repetition with Reusable Objects Handling Exceptions • The try statement identifies a block of statements that may potentially throw an exception • The throw statement transfers execution from the method that caused the exception to the handler – Transfers execution to the catch statement if the throw is placed within a try statement • The catch statement identifies the type of exception being caught and statements to describe or fix the error • The finally statement is optional and is always executed regardless of whether an exception has taken place – Placed after the catch statement
  • 19. 19Chapter 4: Decision Making and Repetition with Reusable Objects
  • 20. 20Chapter 4: Decision Making and Repetition with Reusable Objects
  • 21. 21Chapter 4: Decision Making and Repetition with Reusable Objects Catch an exception Throw an exception
  • 22. 22Chapter 4: Decision Making and Repetition with Reusable Objects Throwing an Exception • Compile the program after coding each method and call statement • Run the program with correct input • Run the program to test the exception handling with invalid input – Alphabetic data – Negative values – Null or zero values • Verify that the user is allowed to reenter data • Verify the program closes correctly
  • 23. 23Chapter 4: Decision Making and Repetition with Reusable Objects Repetition Structure
  • 24. 24Chapter 4: Decision Making and Repetition with Reusable Objects The getSales() method
  • 25. 25Chapter 4: Decision Making and Repetition with Reusable Objects The getCode() method
  • 26. 26Chapter 4: Decision Making and Repetition with Reusable Objects The Case Structure • A type of selection structure that allows for more than two choices when the condition is evaluated • Used when there are many possible, valid choices for user input • The code evaluates the user choice with a switch statement and looks for a match in each case statement • Each case statement contains a ending break statement which forces exit of the structure
  • 27. 27Chapter 4: Decision Making and Repetition with Reusable Objects
  • 28. 28Chapter 4: Decision Making and Repetition with Reusable Objects The getComm() Method
  • 29. 29Chapter 4: Decision Making and Repetition with Reusable Objects Arguments and Parameters • When a method is called, the calling method sends arguments; the called method accepts the values as parameters • Different but related identifier names for the arguments and the parameters should be used for good program design – The variables are only visible in their respective methods • Arguments and parameters for a called method and the calling statement must be of the same number, order, and data type
  • 30. 30Chapter 4: Decision Making and Repetition with Reusable Objects Formatting Numeric Output • The DecimalFormat class formats decimal numbers into Strings for output • Supports different locales, leading and trailing zeros, prefixes/suffixes, and separators • The argument is a pattern, which determines how the formatted number should be displayed
  • 31. 31Chapter 4: Decision Making and Repetition with Reusable Objects
  • 32. 32Chapter 4: Decision Making and Repetition with Reusable Objects The output() method
  • 33. 33Chapter 4: Decision Making and Repetition with Reusable Objects The finish() method Exits system when program completes successfully
  • 34. 34Chapter 4: Decision Making and Repetition with Reusable Objects Moving to the Web • Create the host document to execute the applet
  • 35. 35Chapter 4: Decision Making and Repetition with Reusable Objects Coding an Applet Stub • Enter general block comments • Import java.awt.*, java.applet.*, java.awt.event.*, and java.text.DecimalFormat • Implement the ItemListener interface to listen for the user choice on a Checkbox • Code the method headers for the init() and the itemStateChanged() method – itemStateChanged() is an ItemListener method to process user choices • Declare variables and construct a Color object
  • 36. 36Chapter 4: Decision Making and Repetition with Reusable Objects
  • 37. 37Chapter 4: Decision Making and Repetition with Reusable Objects Making Decisions in Applets • Use a CheckboxGroup to allow user choices
  • 38. 38Chapter 4: Decision Making and Repetition with Reusable Objects Constructing Applet Components • Construct Labels for input and output • Construct a CheckboxGroup for user options
  • 39. 39Chapter 4: Decision Making and Repetition with Reusable Objects Constructing Applet Components • Add Labels and CheckboxGroup to the applet • Add an ItemListener to each Checkbox component with the addItemListener() method • Add color with the setForeground() and the setBackground() methods • Set the insertion point with the requestFocus() method
  • 40. 40Chapter 4: Decision Making and Repetition with Reusable Objects The init() Method
  • 41. 41Chapter 4: Decision Making and Repetition with Reusable Objects Handling Exceptions • Check for valid data when the itemStateChanged() method is triggered, which happens when the user clicks an option button
  • 42. 42Chapter 4: Decision Making and Repetition with Reusable Objects The getSales() Method • Parse the data from the TextField and return a valid sales amount or throw an exception to the init() method
  • 43. 43Chapter 4: Decision Making and Repetition with Reusable Objects The getCode() Method • Initialize the code to 0 • Use nested if statements to assess the boolean state of the Checkboxes and return the code to init()
  • 44. 44Chapter 4: Decision Making and Repetition with Reusable Objects The getComm() Method • Identical to the application • Return the commission value to init()
  • 45. 45Chapter 4: Decision Making and Repetition with Reusable Objects The output() Method • Send output to the Label using setText() • Construct and use DecimalFormat, using the special character # to make a leading zero absent
  • 46. 46Chapter 4: Decision Making and Repetition with Reusable Objects The paint() Method • Display a graphic
  • 47. 47Chapter 4: Decision Making and Repetition with Reusable Objects Compiling and Testing the Applet • Compile the applet • Execute the applet using AppletViewer • Test exception handling by clicking an option button and then typing invalid data into the text box • Verify the error message and the data clearing mechanisms • Test all options with valid data • Test in a browser window • Document the applet interface and source code
  • 48. 48Chapter 4: Decision Making and Repetition with Reusable Objects Chapter Summary • Design a program using methods • Code a selection structure to make decisions in code • Describe the use of the logical AND, OR, and NOT operators • Define exceptions and exception handling
  • 49. 49Chapter 4: Decision Making and Repetition with Reusable Objects Chapter Summary • Code a try statement and a catch statement to handle exceptions • Create a user-defined method • Code a repetition structure using the while statement • Write a switch statement to test for multiple values in data
  • 50. 50Chapter 4: Decision Making and Repetition with Reusable Objects Chapter Summary • Format numbers using a pattern and the format() method • Construct a Color object • Use a Checkbox and a CheckboxGroup in the user interface
  • 51. Java Programming, 3e Concepts and Techniques Chapter 4 Complete