Title: CS 303E Lecture 6 Selection / Conditionals: if and if-else statements
1CS 303E Lecture 6Selection / Conditionalsif
and if-else statements
As soon as questions of will or decision or
reason or choice of action arise, human science
is at a loss.Noam Chomsky
2Linear flow of control
- In method button clicked, all we have seen so far
is one statement after another - The program must execute each statement in the
order written. It cant decide what to do next. - radius radiusField.getNumber()
- area 3.14 radius radius
- areaField.setNumber (area)
- areaField.setPrecision(2)
From CircleArea
3Branching making decisions
- If the condition is true, execute statement_1
- otherwise, execute statement_2
- The condition is an expression that can be true
or false, such as x gt 0
4Branching example
- An example for a checking account
- The account gets interest or a penalty depending
on whether the balance is over 0.
5Empty false branch
- If the condition is true, execute statement
- otherwise, do nothing
- Condition is an expression that can be true or
false.
false
6Syntax -- if Statement
- if (condition) // one-way branch
- statement1
- statement2
- statement3
- if (condition) // two-way branch
- statement
- else
- statement
7if Statement Examples
- if (sales gt 5000)
- commission commission 1.1
- if (balance gt 0)
-
- interest balance INT_RATE
- balance balance interest
-
- else
-
- balance balance - penalty
8Compound Statements
- Often, one statement isnt enough.
- So use a compound statement
-
- statement
- . . . zero or more statements
- statement between braces
-
9if with Compound Statements
- if (condition) if (condition)
- statement statement
- . . . . . .
- statement statement
-
- else
- statement
- . . .
-
10Example
- // Pay at payRate with time and one half for
- // overtime
- pay hoursWorked payRate
- if (hoursWorked gt 40)
- overtime hoursWorked - 40
- pay pay overtime (payRate / 2)
11Conditions orBoolean Expressions
- Condition is another name for boolean expression
-- an expression that evaluates to true or false. - One form of condition is
- expression relop expression
- where relop is a relational operator.
12Boolean Relational Operators
- Math Name Java Java Example
- equal balance 0
- ? not equal ! answer ! y
- gt greater than gt expenses gt income
- ? greater than or equal gt points gt 60
- lt less than lt pressure lt max
- ? less than or equal lt expenses lt income
13Boolean Expression Examples
- count 1 gt a b
- far - near gt 10
- Relational operators have lower precedence
- than arithmetic operators. The expressions are
evaluated before the comparison. - Invalid
- a lt b lt c // syntax error
- a b c // syntax error
14Indentation Helps Programmers but Java Ignores it.
- if (hours gt 40)
-
- over hours - 40
- pay pay over (rate / 2)
All simple statements within another statement
should be indented further to the right than the
outer statement. The two assignment statements
are within the if. All statements in a sequence
of statements in a compound statement should be
indented the same amount, as the two assignment
statements are.
15What Does This Program Do?
- import java.awt.import BreezyGUI.import
java.math.public class - Class extends GBFrameIntegerField z
addIntegerField - (0,1,1,2,1)Button publiCaddButton("Sure",3,2,1,1
)DoubleField Z - addDoubleField(0,2,1,2,1)Button
jaddButton("Yea, whatever",3,1 - ,1,1)int buttondouble integerFielddouble gint
kpublic void - buttonClicked(Button buttonObj)buttonz.getNumber
()if(buttonObj - j)integerFieldMath.pow(0.5,
button)Z.setNumber(integerField) - else if(buttonObjpubliC)integerField(double)
1/buttonZ. - setNumber(integerField)public
- static void main(String args)Frame frmnew
Class()frm.setSize( - 300,200)frm.setVisible(true)
- A little hard to tell, isnt it?
16Multi-way Decisions
17Multi-way Decisions
- Assume outField is a TextField for display
- if (balance gt 0)
- outField.setText (Positive)
- else if (balance lt 0)
- outField.setText (Negative)
- else
- outField.setText (Zero)
- Compound statements can be used here too.
18Nested conditionals CircleAreaAndRadius (p. 76)
19- CircleAreaAndRadius -- Text p. 76.
- import java.awt.
- import BreezyGUI.
- public class CircleAreaAndRadius extends GBFrame
-
- Label radiusLabel addLabel
("Radius",1,1,1,1) - DoubleField radiusField addDoubleField
(0,1,2,1,1) - Label areaLabel addLabel ("Area",2,1,1,1)
- DoubleField areaField addDoubleField
(0,2,2,1,1) - Button radiusButton
- addButton ("Compute Radius",3,1,1,1)
- Button areaButton addButton ("Compute
Area",3,2,1,1) - double radius, area
20- public void buttonClicked (Button buttonObj)
- if (buttonObj areaButton)
- radius radiusField.getNumber()
- area Math.PI radius radius
- areaField.setNumber (area)
-
- else
- area areaField.getNumber()
- if (area gt 0)
- radius Math.sqrt (area / Math.PI)
- radiusField.setNumber (radius)
-
- else
- messageBox ("Error The area must not
be\n" - "a negative number.")
-
21- public static void main (String args)
- Frame frm new CircleAreaAndRadius()
- frm.setSize (200, 150)
- frm.setVisible (true)
-
22CS 303E Lecture 7Selection II (and a little
design)
You know you've achieved perfection in design,
not when you have nothing more to add,but when
you have nothing more to take away.-Antoine de
Saint Exupery.
23Designing a Program
- 1. Design interface
- A Label and Field for each datum.
- One or more Buttons for computation.
- 2. Design computation
- Get input.
- Compute result.
- Display result.
- (There are many more complex patterns.)
24Step-Wise Refinement
- Or top-down implementation
- Start with a general outline.
- Refine each piece by adding detail.
- Refine each detail with more detail, as
necessary. - Keep the pieces separate -- dont mix them up.
- Book mentions waterfall. Not used anymore!!
25More on stepwise Refinement
- Dont follow the Analysis-Design-Implement-Integra
te(Test) cycle blindly. - Better to
- Design a little
- Code a little
- Test a little
- Repeat
- may not need to do this for small projects, but
dont get use to it.
26Logical Operators --
- (and)
- boolean_expression may be
- boolean_expression boolean_expression
- Truth Table for the boolean and operator
- p and q are both boolean expressions
- p q p q
- false false false
- false true false
- true false false
- true true true
27Logical Operators --
- (or)
- boolean_expression may be
- boolean_expression boolean_expression
- Truth Table for the boolean and operator
- p and q are both boolean expressions
- p q p q
- false false false
- false true true
- true false true
- true true true
28Logical Operators -- !
- ! (not)
- boolean_expression may be
- ! boolean_expression
- Truth Table for the boolean and operator
- p is a boolean expression.
- p !p
- false true
- true false
29Type Boolean
- boolean b1, b2, b3
- int i 3, j 4, k 5
- b1 true
- b2 i lt j // value is true or false
- b3 j lt k
- private boolean isPrime (int number)
- . . .
- return false
- . . .
- return true
30Type Boolean
- Used in loops and if statements to control
computation. - if (b1)
- outField.setText(Yes!)
- Used with logical operators
- (AND) (OR) ! (NOT)
31Boolean Variables
Examples boolean chk a gt 0 (b lt 0 c lt
0) boolean dataOk false . . . dataOk
name.equals(inputName)
id.equals(inputId) numberField.isValid
() numberField.getNumber() gt 0
.
32Logical Operators Truth Tables
33Evaluation
exp1 exp2 . . . expn Evaluate left to
right, stop and return true when first exp is
true short circuit evaluation. if all are
false, return false. exp1 exp2 . . .
expn Evaluate left to right, stop and return
false when first exp is false short circuit
evaluation. if all are true, return true.
.
34Nested ifs and
if (cond1) if (cond2) . if
(condn) statement // Is equivalent
to if (cond1 cond2 . . condn)
statement The correct style depends on the
situation. Sometimes nested if better, sometime
compound boolean statement
.
35The switch Statement
- Another way to do some multiway selection is via
the switch statement - switch(expression)
-
- case literal 1
- group of statements
- break
- case literal 2
- group of statements
- break
-
- case literal n
- group of statements
- break
- default
- group of statements
- break
-
-
36The switch Statement
- Can be used in some cases as an alternative to
multiple if - else if - else statements. - Limited in its usefulness
- the controlling expresion must evaluate to an
integer or a character, (another primitive data
type.) - The cases must be constant expressions. They may
only be constants or literals. - Missing break evaluation continues looking for a
match
37The Assignment that Could Have Been
- Request
- Write a program to allow a user to play
rock-paper-scissors against the computer. Keep a
track of how many games each player wins and the
number of ties - Okay, Go.
38Analysis
- Questions for the requestor?
39Design
40Implementation
- public void buttonClicked(Button buttonObj)