Decision Structures1
Decision Structures1
COMPUTER SCIENCE I
DECISION STRUCTURES
DECISION STRUCTURES
Yes/No or
Are you No True/False
at least Question
21?
Yes
Boolean false
Expression
true
Statement
== Equal to
!= Not equal to
QUIZ TIME!
Determine whether the following expressions evaluate to true or
false:
4 + 2 != 6
8 < 15
2.5 > 5.8
2 * 16 < 97
JAVA IF STATEMENTS
if(age >= 21)
drinkingAge = true;
True/False
Question
if(quizScore == 10)
perfectScore = true;
Conditionally Executed
Statement
if(score > = 90)
grade = 'A';
Statement executes
regardless
if(quizScore = 10)
perfectScore = true; This is an assignment operator!
if(quizScore == 10)
perfectScore = true; THIS is the equality operator!
HOW DOES IT WORK?
import javax.swing.JOptionPane;
If the user enters 27…
JOptionPane.showMessageDialog(null, "Goodbye!");
}
}
This line will be executed.
import javax.swing.JOptionPane;
If the user enters 19…
JOptionPane.showMessageDialog(null, "Goodbye!");
}
}
This line will be SKIPPED.
Note: Assume any variables you wish to use have already been
declared.
MULTIPLE CONDITIONALLY EXECUTED STATEMENTS
if(drinkingAge)
System.out.println("You deserve a drink!")
if(ch == 'A')
System.out.println("The letter is A.");
if(BooleanExpression)
statement or block;
else
statement or block;
HOW DOES IT WORK?
import javax.swing.JOptionPane;
If the user enters 27…
JOptionPane.showMessageDialog(null, "Goodbye!");
}
}
import javax.swing.JOptionPane;
If the user enters 19…
JOptionPane.showMessageDialog(null, "Goodbye!");
}
}
This line will be executed.
This line will be SKIPPED.
And so will this line…
GIVE IT A GO!
Rewrite these statements to include an else statement:
Note: Assume any variables you wish to use have already been
declared.
NESTED IF STATEMENTS
if(BooleanExpression) To test more than one condition, an if
{ statement can be nested inside
statement or block; another if statement.
}
else
{
if(BooleanExpression)
{
statement or block;
}
else
{
if(BooleanExpression)
{
statement or block;
}
}
}
IF-ELSE-IF
The if-else-if statement tests a series of conditions.
Simpler than nested if-statements
if(BooleanExpression)
{
statement or block;
}
else if(BooleanExpression)
{
statement or block;
}
else
{
statement or block;
}
COMPARING STRINGS
Strings are reference variables
String name1 = "Bob";
String name2 = "Sam";
if(name1 == name2)
The if statement compares the addresses the objects point to rather
than the values.
To compare correctly:
Use methods of the String class
MORE STRING METHODS
Method Name Description Example