CS 303E Lecture 6 Selection / Conditionals: if and if-else statements
-
Upload
mckenzie-may -
Category
Documents
-
view
34 -
download
0
description
Transcript of CS 303E Lecture 6 Selection / Conditionals: if and if-else statements
CS303E Selection:if and if-else statements 1
CS 303E
Lecture 6
Selection / Conditionals:
if and if-else statementsAs soon as questions of will or decisionor reason or choice of action arise, human science is at a loss.Noam Chomsky
CS303E Selection:if and if-else statements 2
Linear flow of controlIn 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 can’t decide what to do next.
radius = radiusField.getNumber(); area = 3.14 * radius * radius; areaField.setNumber (area); areaField.setPrecision(2);
Statement_1 Statement_2 Statement_3
From CircleArea
CS303E Selection:if and if-else statements 3
Branching = 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 > 0
Statement_1
Statement_2
Condition
true
false
CS303E Selection:if and if-else statements 4
Branching exampleAn example for a checking account:
The account gets interest or a penalty depending on whether the balance is over 0.
balance = balance + interest;
balance = balance – penalty;
balance > 0
true
false
CS303E Selection:if and if-else statements 5
Empty false branch
If the condition is true, execute statement;
otherwise, do nothing:
Condition is an expression that can be true or false.
false
Statement
Condition
true
CS303E Selection:if and if-else statements 6
Syntax -- if Statement
if (condition) // one-way branch
statement1;
statement2;
statement3;
if (condition) // two-way branch
statement;
else
statement;
CS303E Selection:if and if-else statements 7
if Statement Examplesif (sales > 5000)
commission = commission * 1.1;
if (balance > 0){
interest = balance * INT_RATE;balance = balance + interest;
}else{
balance = balance - penalty;}
CS303E Selection:if and if-else statements 8
Compound StatementsOften, one statement; isn’t enough.
So use a compound statement :
{
statement;
. . . zero or more statements
statement; between braces {…}
}
CS303E Selection:if and if-else statements 9
if with Compound Statements
if (condition) if (condition) { statement; { statement;
. . . . . .statement; statement;
} }else { statement;
. . .}
CS303E Selection:if and if-else statements 10
Example
// Pay at payRate with time and one half for
// overtime:
pay = hoursWorked * payRate;
if (hoursWorked > 40)
{ overtime = hoursWorked - 40;
pay = pay + overtime * (payRate / 2);
}
CS303E Selection:if and if-else statements 11
Conditions 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.
CS303E Selection:if and if-else statements 12
Boolean Relational Operators
Math Name Java Java Example
= equal = = balance = = 0
not equal != answer != ‘y’
> greater than > expenses > income
greater than or equal >= points >= 60
< less than < pressure < max
less than or equal <= expenses <= income
CS303E Selection:if and if-else statements 13
Boolean Expression Examples
count + 1 > a * b
far - near >= 10
Relational operators have lower precedencethan arithmetic operators. The expressions are evaluated before the comparison.
Invalid:
a < b < c // syntax error
a == b == c // syntax error
CS303E Selection:if and if-else statements 14
Indentation Helps Programmers but Java Ignores it.
if (hours > 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.
CS303E Selection:if and if-else statements 15
What Does This Program Do?import java.awt.*;import BreezyGUI.*;import java.math.*;public class
Class extends GBFrame{IntegerField z = addIntegerField
(0,1,1,2,1);Button publiC=addButton("Sure",3,2,1,1);DoubleField Z
=addDoubleField(0,2,1,2,1);Button j=addButton("Yea, whatever",3,1
,1,1);int button;double integerField;double g;int k;public void
buttonClicked(Button buttonObj){button=z.getNumber();if(buttonObj
==j){integerField=Math.pow(0.5, button);;;Z.setNumber(integerField)
;}else if(buttonObj==publiC){integerField=(double)1/button;Z.
setNumber(integerField);;}}public
static void main(String[] args){Frame frm=new Class();frm.setSize(
300,200);frm.setVisible(true);}}
A little hard to tell, isn’t it?
CS303E Selection:if and if-else statements 16
Multi-way Decisions
Several possible paths:
display “Positive”
display “Negative”
balance > 0
true
false
balance < 0
true
display “Zero”
false
CS303E Selection:if and if-else statements 17
Multi-way Decisions
Assume outField is a TextField for display:
if (balance > 0)outField.setText (“Positive”);
else if (balance < 0)outField.setText (“Negative”);
elseoutField.setText (“Zero”);
Compound statements can be used here too.
CS303E Selection:if and if-else statements 18
Nested conditionals CircleAreaAndRadius (p. 76)
Compute area or radius?
Compute area from radius;Display area;area
radius > 0?
radiusCompute radius from area;Display radius;
Display error message;
yes
no
CS303E Selection:if and if-else statements 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;
CS303E Selection:if and if-else statements 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 >= 0)
{ radius = Math.sqrt (area / Math.PI);
radiusField.setNumber (radius);
}
else
messageBox ("Error: The area must not be\n"
+ "a negative number.");
}
}
CS303E Selection:if and if-else statements 21
public static void main (String[] args)
{ Frame frm = new CircleAreaAndRadius();
frm.setSize (200, 150);
frm.setVisible (true);
}
}
CS303E Selection:if and if-else statements 22
CS 303E
Lecture 7:
Selection 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.
CS303E Selection:if and if-else statements 23
Designing 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.)
CS303E Selection:if and if-else statements 24
Step-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 -- don’t mix them up. Book mentions waterfall. Not used anymore!!
CS303E Selection:if and if-else statements 25
More on stepwise Refinement Don’t follow the Analysis-Design-Implement-
Integrate(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 don’t get use to it.
CS303E Selection:if and if-else statements 26
Logical Operators -- &&&& (and):
boolean_expression may be:
boolean_expression && boolean_expressionTruth Table for the boolean and operatorp and q are both boolean expressions
p q p && qfalse false falsefalse true falsetruefalse falsetruetrue true
CS303E Selection:if and if-else statements 27
Logical Operators -- |||| (or):
boolean_expression may be:
boolean_expression || boolean_expressionTruth Table for the boolean and operatorp and q are both boolean expressions
p q p || qfalse false falsefalse true truetruefalse truetruetrue true
CS303E Selection:if and if-else statements 28
Logical Operators -- !
! (not):
boolean_expression may be:
! boolean_expressionTruth Table for the boolean and operatorp is a boolean expression.
p !pfalse truetruefalse
CS303E Selection:if and if-else statements 29
Type Boolean
boolean b1, b2, b3;int i = 3, j = 4, k = 5;b1 = true;b2 = i < j; // value is true or falseb3 = j <= k;
private boolean isPrime (int number){ . . . return false; . . . return true;}
CS303E Selection:if and if-else statements 30
Type Boolean
Used in loops and if statements to control computation.
if (b1)
outField.setText(“Yes!”);
Used with logical operators:&& (AND) || (OR) ! (NOT)
CS303E Selection:if and if-else statements 31
Boolean Variables
Examples:
boolean chk = a > 0 && (b <= 0 || c <= 0);
boolean dataOk = false;. . .dataOk = name.equals(inputName) && id.equals(inputId) && numberField.isValid() && numberField.getNumber() > 0;
.
CS303E Selection:if and if-else statements 32
Logical Operators Truth TablesA B A || B A && B
true true true truetrue false true falsefalse true true falsefalse false false false
A ! Atrue falsefalse true
CS303E Selection:if and if-else statements 33
Evaluationexp1 || 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.
.
CS303E Selection:if and if-else statements 34
Nested 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
.
CS303E Selection:if and if-else statements 35
The 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;
}
CS303E Selection:if and if-else statements 36
The 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
CS303E Selection:if and if-else statements 37
The 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.