You are on page 1of 14

CHAPTER 12 Decision Making

This chapter looks at how computer programs make decisions about


numbers and variables using the if statement. This statement is one of the
fundamental building blocks used in creating large programs.
Chapter Topics:

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?

The answer to the question is either true or false.


If the answer is true,
o follow the line labeled true,
o do the directions in the box "wipers on",
o follow the line to "continue".
If the answer is false,
o follow the line labeled false,
o do the directions in the box "wipers off",

o follow the line to "continue".


QUESTION 2:
How many ways can you go from "start" to "continue"?
A good answer might be:
There are two paths through this chart.

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.

If the answer is "false" only the false-branch is executed.


No matter which branch is chosen, execution continues with the
statement after the false-branch.
Notice that a two-way decision is like picking which of two roads to take to
the same destination. The fork in the road is the if statement, and the two
roads come together just after the false-branch.
QUESTION 3:
The user runs the program and enters "12". What will the
program print?
A good answer might be:
Enter an integer:
12
The number 12 is positive
Good-bye for now

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");
}

System.out.println("Good-bye for now");

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

Here is a simulation of this program (using JavaScript and your browser). Of


course, for maximum benifit you should "copy-paste-save-and-run" the real
program. But, play with the following if you want. Perform the steps 1, 2, and
3 under the simulated monitor as many times as you want. (Note: if this
does not work, your browser does not have JavaScript enabled. Skip this
and go on to the next page.)

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");
}
}

C:> javac NumberTester.java


C:> java NumberTester
Enter an integer:
5

The number 5 is positive


Good-bye for now
C:>

1. Start the program


2. Click in the "monitor" window after
the last line and enter a number
3.Continue

This is just a simulation (using JavaScript), so it is not exactly like a


compiling and running a real Java program. Don't take it too seriously.
Please do the real thing if you can.
QUESTION 5:

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

Here is the program again with some added statements:


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;

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
}
}

System.out.println("Good-bye for now");

// always executed

To include more than one statement in a branch, enclose the statements


with braces, { and }. A group of statements grouped together like this is
called a block statement, (or usually, justblock.) There can be as many
statements as you want in a block. A block can go anyplace a single
statement can go. All the statements in the true block are executed when
the answer to the question is true.
Of course, all the statements in the false block are executed when the
answer to the question is false. The false block consists of the block that
follows the else. Notice that the very last statement in the program is not
part of the false block.
QUESTION 6:

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.

Outline of a Two-way Decision


Here is how an outline of how make a two-way decision:
... statements done before the decision
if ( condition )
.... // true branch
else

....

// false branch

... statements done after the branch comes back together

Here are some details:


The condition evaluates to true or false, often by comparing variables
and values.
The else divides the true branch from the false branch.
The statement after the false branch (or false block) always will be
executed.
A block consists of several statements inside a pair of braces, { and }.
The true branch can be a block.
The false branch can be a block.
There can be as many statements in a block as you need.
When a block is chosen for execution, the statements in it are executed
one by one.
The condition can compare what is held in a variable to other values. You
can use the comparisons: <, >, and so on. (More about these later.) The first
statement after the false branch will be executed no matter which branch is
chosen. The if-else is like a fork in the road, but the road always comes
together again.
QUESTION 7:
Do you believe that the following section of a program is correct?
if ( num < 0 )
System.out.println("The number " + num + " is negative");

else

System.out.println("The number " + num + " is positive");


System.out.print ("positive numbers are greater ");
System.out.println("or equal to zero ");
System.out.println("Good-bye for now");
A good answer might be:

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

The false block was not put inside braces:


if ( num < 0 )
System.out.println("The number " + num + " is negative");
else
System.out.println("The number " + num + " is positive");
System.out.print ("positive numbers are greater ");
System.out.println("or equal to zero ");
System.out.println("Good-bye for now");

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:

//
//
//
//
//

How would you fix the above program section?


A good answer might be:
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 ");
false-branch

//

//
//

System.out.println("or equal to zero ");


false-branch
}
System.out.println("Good-bye for now");
always executed

//
//

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

Box Office Program


Here is the complete program, with the blank
filled in correctly:
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 );
if ( age < 17 )
{
System.out.println("Child
rate.");
}
else
{
System.out.println("Adult
rate.");
}
System.out.println("Enjoy the
show.");
}
}

Here is what happens for one run of


the program:
1. The program prints "Enter your
age".
2. The user enters an age---21,
for example.
3. The 21 is converted from
characters into int and put into
the variable age.
4. The condition age < 17 is
tested.
5. 21 < 17 is false.
6. The false branch is executed:
the program prints "adult
rate".
7. Execution continues with the
statement after the false
branch: "Enjoy the show" is
printed.

QUESTION 10:
What does the program output if the user enters 16?
A good answer might be:
Enter your age

Table of Relational Operators


Operator

Meaning

A == B

is A equal to B ?

A < B

is A less than B ?

A <= B

is A less than or equal to B ?

A > B

is A Greater than B ?

A >= B

is A Greater than or equal to 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:

As practice, fill in the blanks in the following chart:


Expression
25 == 25

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

A good answer might be:


Expression

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

Using Boolean Expressions

In an if statement, the true or false of a boolean expression picks whether


the true branch or the false branch of code is executed. To practice putting
together programs with two-way decisions, let us look at another story
problem.
A clothing store wants a program that calculates the tax on an item. Clothing
that costs $100 or more has a 5% tax. Clothing that costs less than $100 is
tax free. Write a program that asks for the price, then calculates the tax and
prints it out, and prints out the total cost of the item.
For simplicity the price will be an integer. All print statements will be placed
after the ifstatement.
Here is a skeleton of the program:
______________
class TaxProgram
{
public static void main (String[] args)
throws IOException
{
____________________
BufferedReader stdin =
__________________________
String inData;
int
price;
double tax ;

Here are some program fragments


to use in filling the blanks:
tax = price * taxRate;
new BufferedReader
( new InputStreamReader(
System.in ) );
inData = stdin.readLine();
double taxRate = 0.05;
price >= 100
import java.io.*;
tax = 0;

System.out.println("Enter the price:");


__________________________
price

= Integer.parseInt( inData );

if ( ________________ )
______________________
else
________
System.out.println("Item cost: " +
price + " Tax: " + tax +
" Total: "
+ (price+tax) );
}
}

QUESTION 12:

Complete the program by filling in the blanks.


A good answer might be:

The answer is given below:


Adding in a Zero

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;

System.out.println("Item cost: " + price +


" Tax: " + tax + " Total: " + (price+tax) );
}
}

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

End of the Chapter


That is the end of this chapter. If you want, you may review the following
topics. Else, go on to the next chapter.
Two-way decisions.
Outline of a Two-way decision.
Statement blocks.
Boolean Expressions.
Table of Relational Operators.
Click on a blue term that interests you to go to where it was discussed. To
get back here, click on the "back arrow" button of your browser. The next
chapter will continue the discussion of decisons.

Back to the main menu.


You have reached the end of the chapter.

You might also like