Professional Documents
Culture Documents
Two-way Decisions.
Java if statement.
Outline of a two-way decision.
Blocks of statements.
Boolean Expressions.
Relational Operators.
Example Programs.
QUESTION 1:
You are driving in your car and it starts to rain. The rain falls on
your windshield and makes it hard to see. Should your
windshield wipers be on or off?
A good answer might be:
On.
Two-way Decisions
The windshield wipers (and many other things in a car) are controlled with
an ON-OFF switch. The decision about the wipers looks like the chart.
In this picture, start at the top, then follow the line to the question:
is it raining?
Decisions
The "windshield wiper" decision is a two-way decision (sometimes called a
"binary" decision.) It seems small, but in programs complicated decisions
are made of many small decisions. Here is a program (suitable for "copypaste-and-run") that includes a binary decision.
import java.io.*;
class NumberTester
{
public static void main (String[] args) throws IOException
{
BufferedReader stdin =
new BufferedReader ( new InputStreamReader( System.in ) );
String inData;
int
num;
System.out.println("Enter an integer:");
inData = stdin.readLine();
num
= Integer.parseInt( inData );
// convert inData to
int
if ( num < 0 )
// is num less than zero?
System.out.println("The number " + num + " is
negative"); // true-branch
else
System.out.println("The number " + num + " is
positive"); // false-branch
System.out.println("Good-bye for now");
}
// always executed
The words if and else are markers that divide the decision into two
sections. The elsedivides the "true branch" from the "false branch".
The if statment always asks a question (often about a variable.)
If the answer is "true" only the true-branch is exectued.
The false branch is executed because the answer to the question num <
0 was false.
The Program as a Chart
Here is the program again, done as a flowchart. Because the answer to the
question is "false", the false branch is performed. The "two-way split" of the
program is easy to see in a two dimensional chart. It is harder to see this in
a program where line follows line one after another.
import java.io.*;
class NumberTester
{
public static void main (String[] args)
throws IOException
{
BufferedReader stdin =
new BufferedReader (
new InputStreamReader( System.in ) );
String inData;
int
num;
System.out.println("Enter an integer:");
inData = stdin.readLine();
num
= Integer.parseInt( inData );
if ( num < 0 )
System.out.println("The number " + num +
" is negative");
else
System.out.println("The number " + num +
" is positive");
}
The flow chart shows the overall logic of the program. Most of the details of
syntax are left out. It is often helpful to sketch a flowchart when you are
designing a program. You can use the flowchart to get the logic correct, then
fill in the details when you write the program.
QUESTION 4:
The user runs the program and enters "-5". What will the program
print?
A good answer might be:
Enter an integer:
-5
The number -5 is negative
Good-bye for now
Only the true-branch was executed because the answer to the question num
< 0 was true.
Simulated Program
import java.io.*;
class NumberTester
{
public static void main (String[]
args)
throws IOException
{
BufferedReader stdin =
new BufferedReader (
new
InputStreamReader( System.in ) );
Simulated Monitor
String inData;
int
num;
System.out.println("Enter an
integer:");
inData = stdin.readLine();
num
=
Integer.parseInt( inData );
if ( num < 0 )
System.out.println("The number "
+ num +
" is negative");
else
System.out.println("The number "
+ num +
" is positive");
System.out.println("Good-bye for
now");
}
}
Try the program (or look at the flowchart) with the value 0 (zero).
What is the output?
A good answer might be:
Enter an integer:
0
The number 0 is positive
Good-bye for now
More than one Statement per Branch
String inData;
int
num;
int
System.out.println("Enter an integer:");
inData = stdin.readLine();
num
= Integer.parseInt( inData );
// convert inData to
if ( num < 0 )
{
System.out.println("The number " + num + " is
negative"); // true-branch
System.out.println("negative number are less than
zero"); // true-branch
}
else
{
System.out.println("The number " + num + " is
positive"); // false-branch
System.out.print ("positive numbers are greater
");
// false-branch
System.out.println("or equal to zero
");
// false-branch
}
}
// always executed
In answer to the question, the user enters a 17. What will the
new program print?
A good answer might be:
Enter an integer:
17
The number 17 is positive
positive numbers are greater or equal to zero
Good-bye for now
The false block was executed because the answer to the question (num <
0) was false. The false block consists of two statements.
....
// false branch
else
No. The programmer probably wants the three statements after the else to
be part of a false block, but has not used braces to show this.
Only One Statement per Branch
Our human-friendly indenting shows what we want, but the compiler will
merely look for braces. It will see the equivalent of:
if ( num < 0 )
System.out.println("The number " + num + " is negative");
true-branch
else
System.out.println("The number " + num + " is positive");
false-branch
System.out.print ("positive numbers are greater ");
always executed
System.out.println("or equal to zero ");
always executed
System.out.println("Good-bye for now");
always executed
QUESTION 8:
//
//
//
//
//
//
//
//
//
//
Notice that in this program that the true branch has one statement, which is
not a block, and that the false branch has one statement, which is a block
(and as a block contains three statements.)
Practice
At a movie theater box office a person less than age 17 is charged the "child
rate". Otherwise a person is charged "adult rate." Here is a partially
complete program that does this:
import java.io.*;
class BoxOffice
{
public static void main (String[] args) throws IOException
{
BufferedReader stdin =
new BufferedReader ( new InputStreamReader( System.in ) );
String inData;
int
age;
System.out.println("Enter your age:");
inData = stdin.readLine();
age
= Integer.parseInt( inData );
// convert inData to
if ( __________________ )
{
System.out.println("Child rate.");
}
else
{
System.out.println("Adult rate.");
}
System.out.println("Enjoy the show.");
// always executed
int
}
}
In this program, the true branch and the false branch are both blocks. Each
block has only one statement inside of it, but this is OK. All you need to do is
complete the blank so the program picks the correct block for the age that
was input.
QUESTION 9:
Fill in the blank of the program. You might wish to make a copy of
the program in NotePad, make your proposed correction, and run
it to see if it works as you think.
A good answer might be:
if ( age < 17
QUESTION 10:
What does the program output if the user enters 16?
A good answer might be:
Enter your age
Meaning
A == B
is A equal to B ?
A < B
is A less than B ?
A <= B
A > B
is A Greater than B ?
A >= B
A != B
is A not equal to B ?
16
Child rate
Enjoy the show
Boolean Expressions
We need to look at the condition part of the ifstatement. Usually this will be
a boolean expression. Recall that an expression is is a combination of
literals, operators, variables, and parentheses used to calculate a value.
A boolean expression is an expression that evaluates to true or false.
Boolean expressions often make comparisons between numbers. A
relational operator says what comparison you want to make.
Notice several details (that will be reallyannoying later on if you forget about
them): the operator for "equal" is == (two equal signs in a row.) In your web
browser it may be hard to see that there are two equal signs. The operator
for "not equal" is != (exclaimation point equal sign.)
QUESTION 11:
Value
true
Expression
25 != 25
Value
False
25 <= 25
True
25 > 25
False
25 >= 25
True
25 = 25
Illegal
-5 < 7
true
-305 <= 97
True
Value
Expression
Value
25 == 25
true
25 != 25
false
25 <= 25
true
25 > 25
false
25 >= 25
true
25 = 25
illegal
-5 < 7
true
-305 <= 97
true
= Integer.parseInt( inData );
if ( ________________ )
______________________
else
________
System.out.println("Item cost: " +
price + " Tax: " + tax +
" Total: "
+ (price+tax) );
}
}
QUESTION 12:
Here is the complete program. The blanks have been filled, and the program
layout improved somewhat. You can "copy-paste-and-run" this program.
import java.io.*;
class TaxProgram
{
public static void main (String[] args) throws IOException
{
double taxRate = 0.05;
BufferedReader stdin =
new BufferedReader ( new InputStreamReader( System.in ) );
String inData;
int
price;
double tax ;
System.out.println("Enter the price:");
inData = stdin.readLine();
price = Integer.parseInt( inData );
if ( price >= 100 )
tax = price * taxRate;
else
tax = 0;
The program might look somewhat odd to you because the arithmetic
expression (price+tax) will sometimes add a zero to price. This is fine.
Sometimes it is easier to add in a zero than to do something special just to
avoid adding it in. The program is shorter and easier to understand if
the println statements are at the end.
QUESTION 13:
The user buys a shirt for $100 What will be printed on the
monitor?
A good answer might be:
Enter the price:
100
Item cost: 100 Tax: 5.0 Total: 105.0