Title: Bobby D. Gerardo
1Programming and Problem Solving Using Java
- Bobby D. Gerardo
- Kunsan National University
- Summer 2004
2Chapter 4Control Structures Decision and Loops
3Review
4Object Oriented Programming
- Objects are key to understanding object-oriented
technology. You can look around you now and see
many examples of real-world objects your dog,
your desk, your television set, your bicycle. - These real-world objects share two
characteristics They all have state and
behavior. For example, dogs have state (name,
color, breed, hungry) and behavior (barking,
fetching, and wagging tail). Bicycles have state
(current gear, current pedal cadence, two wheels,
number of gears) and behavior (braking,
accelerating, slowing down, changing gears).
5Object Oriented Programming (cont)
- Software objects are modeled after real-world
objects in that they too have state and behavior.
A software object maintains its state in one or
more variables . A variable is an item of data
named by an identifier. A software object
implements its behavior with methods . A method
is a function (subroutine) associated with an
object. - object-oriented design
- A software design method that models the
characteristics of abstract or real objects using
classes and objects.
6Encapsulation
- Because all data fields have private visibility
(FoodItem Example), another class that is a
client (user) of the class FoodItem cannot access
the field directly. - To change the data field value, the client must
invoke one of the mutator methods. - To retrieve a data field value, the client must
invoke one of the accesor methods. - This is the principle of encapsulation.
7Methods
- Constructor Methods always has the same name as
the class. It should have the public visibility
and does not have a result type because it does
not return a value. - Accessor Methods accessor methods are sometimes
called getter methods and should begin with the
word get. - Mutator Methods Just as we need to access an
objects private o protected data from another
object, we sometimes need to store data in an
objects private or protected fields. We use
mutator or modifier methods to do this.
8Case Study Solution Format
- Problem specify the problem requirement
- Analysis analyze the problem an identify the
classes that will be needed - Design design the classes to solve the problem.
Locate the relevant classes in libraries. Modify
existing classes if necessary. Design new classes
where necessary - Implementation implement the new and modified
classes. - Testing test and verify the completed program.
9Review Exercise
10Review Exercise
- What is an accessor?
- 2. What is a default constructor?
- 3. Explain the relationship between a browser and
an applet? Which one support object? - 4. The method paint() has an argument g of type
Graphics. Explain what this object does in the
paint() method?
11Answer Review Exercise
- What is an accessor?
- Accessor methods are sometimes called getter
methods and should begin with the word get. - 2. What is a default constructor?
- It should have the public visibility and does not
have a result type because it does not return a
value. - 3. Explain the relationship between a browser and
an applet? Which one support object? - An applet is a Java class that has an associated
drawing surface. It is intended as a support
object in a larger context such as web browser
like IE or Netscape. - 4. The method paint() has an argument g of type
Graphics. Explain what this object does in the
paint() method? - It represent an instance of the Graphics class
(the graphics context or drawing surface passed
by the browser or applet viewer) so that we may
call the methods of the Graphics class.
12Chapter 4Control Structures Decision and Loops
13Control Structures and Statements
- Statements that control the flow of execution in
a program or method. - Study of boolean expressions.
- Decision making using if and switch statements.
- We will study also loops such as counting loops
and state-controlled loops. - Java loop control statements, while and for.
144.1 Control Structures (1)
- Structured programming uses control structures to
control the flow of execution in a program or
method. - Three kinds of control structure
- Sequence
- Selection
- Repetition
154.1 Control Structures (2)
- A compound statement or block, written a group of
statements bracketed by and, is used to specify
sequential flow. - Selection control structures enable the method
to select or chose one step from several
alternative algorithm steps. i.e. if and switch. - Repetition control structures enable the
programmer to specify that a block of statements
should be repeated. i.e. loop body, while and for
statements.
164.1 Control Structures (3)
- Selection control structures enable the method
to select or chose one step from several
alternative algorithm steps. i.e. if and switch. - Repetition control structures enable the
programmer to specify that a block of statements
should be repeated. i.e. loop body, while and for
statements.
174.2 boolean Expressions
- boolean expressions or, conditions, facilitate
comparison. - Two possible values true or false
- The simplest boolean expression is a boolean
variable or boolean literal (true or false). - Table 4.1 shows Java relational operators
- Example 4.2 and Table 4.2 shows some example
conditions
18Java Relational Operators
- Operator Meaning
- lt Less than
- lt Less than or equal
- gt Greater than
- gt Greater than or equal
- Equal to
- ! Not equal
19boolean Operators
- We can form more complicated boolean expressions
by using the three boolean operators - (1) (and) (2) (or) (3) ! (not)
- Example
- a. (salaryltminimumSalary) (dependentsgt5)
- b. (temperaturegt90.0) (humidity gt 0.90)
- c. (salarygt 15000.00) (salary lt 2000.00)
20Case Study 1 Payroll Problem
21Case Study 1 Payroll Problem
- 1. Problem Your company pays its employees
time and a half for all hours worked over 40
hours a week. Employees who earns more than 100
a week pay union dues of 25 per week. Write a
program to compute an employees gross pay and
net pay - 2. Analysis analyze the problem an identify the
classes that will be needed - 3. Design design the classes to solve the
problem. Locate the relevant classes in
libraries. Modify existing classes if necessary.
Design new classes where necessary - 4. Implementation implement the new and
modified classes. - 5. Testing test and verify the completed
program.
22Modified Case Study1
- Modify method computeNet to deduct union dues of
10 for gross salary over 100 and 5 otherwise.
Also deduct a 3 city wage tax for all employees.
23Summary of Programming Exercises and Projects
(Chap. 3)
- Exercises
- Figure 3.34 P. 159
- Modify Fig. 3.34 to draw Red and blue lines at
position 240X340 - Figure 3.37 P. 162- Class House
- Modify Fig. 3.37 to use brown lines and red door.
- Figure 3.42 P. 166- Class HappyFace
- Modify Fig. 3.42 with eyes and nose filled with
yellow color. - Projects
- No.1 P. 177 Projectile Problem
- No. 7 P. 179 Bar Graph.
24Summary of Programming Exercises(Chap. 4)
- Case Study 1 Payroll Problem
- Modify method computeNet to deduct union dues of
10 for gross salary over 100 and 5 otherwise.
Also deduct a 3 city wage tax for all employees.
25boolean Operators (cont)
- Table 4.3 The (and) operator
- Table 4.4 The (or) operator
- Table 4.5 The ! (not) operator
26Table 4.6 Operator Precedence
- Operator Description
- !, (unary), -(unary) Logical not, uniray plus,
uniray minus - , /, Multiplication, Division, Remainder
- , - Addition, subtraction
- lt, lt, gt, gt Relational inequality
- , ! Equal, Not Equal
- Logical and
- Logical or
- Assignment
27Short-Circuit Evaluation of boolean Expressions
- When evaluating boolean expressions involving the
operators and , Java employs a technique
called Short-Circuit Evaluation . - This means that Java stops evaluating a boolean
expression as soon as its value can be
determined. - For example the value of flag is true, the
expression - flag (xgt0 y ! 7.5)
28Writing English Conditions in Java
- To solve programming problems, we write English
conditions as boolean expressions. Often we want
to test whether a variable has one of several
possible values. - For example if ch is type char, we may want to
know if ch is the letter a or A. - (cha)(chA) //true
- cha A //not valid
- (cha) (chA) //not valid
29Range of values
- (x gt min) (x lt max) //x is included
- (x gt min) (x lt max) //x is not included
- ! ((x gt min) (x lt max)) //negated
- (x lt min) (x gt max) //equivalent
30De Morgans Theorem
- Use simpler expressions using De Morgans
theorem - 1. !(expression1 expression2) equals !
expression1!expression2 - ! ((x gt min) (x lt max) equals !(x gt min)
! (x lt max) - 2. !(expression1 expression2) equals !
Expression1 !expression2 - !((ch a) (ch A)) equals ! (ch
a) ! (ch A)
31Character comparison
- The order of char comparison is based on the
unicode position of each character (apprendix B). - The first 128 characters of Unicode correspond to
the ASCII code.
32Comparing String Equality
- We can also compare String objects
- Use methods in class String, not relational
operators. - Use method equals (not the equality operator )
- i.e. string1.equals(string2)
33Method equalsIgnoreCase()
- aces.equals(ACES) is false
- aces.equalsIgnoreCase(ACES) is true
34Lexicographic Comparison of Strings
- Java, provides a method compareTo(), that you can
use to compare strings lexicographically. The
lexicographic order of two strings is the order
in which they would normally appear in a
dictionary. - i.e. string.compareTo(string2)
- Has a negative value if string1 is
lexicographically less than string2. - Has the value of 0 if string1 is
lexicographically equal to string2. - Has a positive value if string1 is
lexicographically greater than string2.
35The if Statement
- In Java, the primary selection control structure
is an if statement. - If statement always contain a boolean expression.
- One consequence
- If (x ! 0.0) product product x
- Two consequence
- If (gross gt 100.00)
- net gross tax
-
- Else
- net gross
36Fig. 4.5 Flowchart of if statements
37If Statement forms
- One consequent
- if (condition)
- statement T
-
- Two consequent
- if (condition)
- statement T
-
- else
- statement F
-
38Decision Steps in Algorithms
- Algorithm steps that select from a choice of
actions are called decision steps. - For example, coded as if statement in Java
- if the first letter is a vowel or y
- dont translate
- else
- translate the word to pig Latin in normal way
39Program Style Choosing variable scope
- When choosing the scope of variables (where
they are accessible), we follow these principles - Keep variables as local as possible
- Avoid a calculation more than once
- Use variables sparingly
40Example, following principle 3
- Method computeNet() does not declare a local
variable (for example, net) to store the method
result (referring to the Fig. 4.13). - public double computeNet(double gross)
- double net
- if (gross lt MAX_NO_DUES)
- net gross
-
- else
- net gross dues // deduct dues amount
-
- return net
41Multiple-Alternative Decisions Nested if and
switch
- In this section we use nested if statements (one
if statement inside another) to code
decisions with multiple alternatives. - //increment numPos, numNeg, or numZero depending
on x - if (x gt 0)
- numPos numPos 1
-
- else
- if (x lt 0)
- numNeg numNeg 1
- else // x is zero
- numZero numZero 1
42Table 4.10 Trace of if Statement in Example 4.14
for x -7
- Statement Part Effect
- If (x gt 0) -7 gt 0 is false
- If (x lt 0) -7 lt 0 is true
- numNeg numNeg1 Add I to numNeg
43Comparison of Nested if and Sequence of ifs
- Beginning programmers often use a sequence of if
statements rather than a single nested if
statement. The nested if statement for Example
4.1.4 is logically equivalent to the following
sequence of if statements - // In efficient sequence of if statements
- if (x gt 0)
- numPos numPos 1
- If (x lt 0)
- numNeg numNeg 1
- If (x 0)
- numZero numZero 1
44Java Rule for Matching else with if
- We use indention and braces to convey the
logical structure of a nested if statement to
the program reader. - See Example 4.15
45Order of the Condition Matters
- When more than one condition in a
multiple-alternative decision is true, only
the task following the first true condition
executes.
46switch Statements
- Java provides a convenient control
structure called switch statement that can be
used to implement a multiple- alternative
decision. - The break statement causes immediate exit from
the switch statements. - See Fig. 4.16
47Counting Loops, while and for Statements
- Counting Loops simplest kind of loop. A loop
that executes a specified number of times is
counting loop (or counter-controlled loop).
48The while Statement
- We first show how to implement a counting loop
using a while statement, the most versatile loop
control statement. A while statement begins with
a word while and has the form - while (repetitionCondition) //controlled by
repetition condition - statement //loop body, statement to be
repeated
49Fig. 4.17 Counting Loop with a while statement
50Loop-Control Variable
- In fig. 4.17 the variable countEmp is called the
loop-controlled variable because its value
determines whether the loop body is repeated. - Initialized set to an initial value
- Tested is tested before the start of loop
repetition - Update is updated during each iteration.
51Fig. 4.18 Flow Chart of a while Loop
52The for Statement
- Because counting loops are so common, most
programming languages provide a special control
statement for implementing them. - In Java, this is the for statement.
- for (int countEmp 0 countEmp lt numberEmp
countEmp countEmp 1)
53Fig. 4.19 Counting Loop with a for statement
54Case Study 2 A Program for Arithmetic Drill and
Practice
55Case Study 2 A Program for Arithmetic Drill and
Practice
- Problem Your little sister would like a
program that gives her some practice in solving
arithmetic problems. She would like program that
can generate and solve arithmetic problems of
varying difficulty and would like to be able to
specify the problem type (addition,
multiplication, and so on) and the difficulty
level (easy, moderate, hard). Your program should
generate a problem and solve it. It should also
compare its solution to your sisters and let her
know whether her solution is correct.
56Modified Case Study 2
- Modify Case Study 2 by displaying the output on a
dialog window instead of displaying in the
console window. Note that your program will use
the javax.swing. package.
57Programming Projects
- Problem 1, P. 243
- Problem 4, p. 243
58? End of Chapter