Sei sulla pagina 1di 11

CHAPTER 12 — Decision Making

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?

Two-way Decisions

The windshield wipers are controlled with an ON-OFF switch. The flowchart at right shows how this decision is
made.

Start at the top of the chart then follow the line to the question:

is it raining?
The answer is either true or false.
 If the answer is true,
o follow the line labeled True,
o perform the instructions in the box "wipers on",
o follow the line to "continue".
 If the answer is false,
o follow the line labeled False,
o perform the instructions in the box "wipers off",
o follow the line to "continue".
QUESTION 2:
How many ways can you go from "start" to "continue"?
Decisions
The windshield wiper decision is a two-way decision (sometimes called a binary decision). The decision seems
small, but in programming, complicated decisions are made of many small decisions. Here is a program
that implements the wiper decision:

import java.util.Scanner;
class RainTester
{
public static void main (String[] args)
{
Scanner scan = new Scanner( System.in );
String answer;

System.out.print("Is it raining? (Y or N): ");


answer = scan.nextLine();

if ( answer.equals("Y") ) // is answer exactly "Y" ?


System.out.println("Wipers On"); // true branch
else
System.out.println("Wipers Off"); // false branch
}
}
The user is prompted to answer with a single character, Y or N :

System.out.print("Is it raining? (Y or N): ");


The Scanner reads in whatever the user enters (even if the user enters more than one character):

answer = scan.nextLine();
The if statement tests if the user entered exactly the character Y (and nothing else):

if ( answer.equals("Y") ) // is answer exactly "Y" ?


If so, then the statement labeled "true branch" is executed. Otherwise, the statement labeled "false branch" is
exectued.

The "true branch" is separated from the "false branch" by the reserved word else.
QUESTION 3:

What happens if the user enters anything other than exactly the character Y ?
Checking a String
The if statement

if ( answer.equals("Y") )

picks either the "true branch" or the "false branch" . Only one branch or the other is executed, just as
in the flow chart. This part of the statement

answer.equals("Y")

evaluates to true if the string referenced by answer contains exactly the single character "Y" . For
anything else it evaluates to false. This is somewhat awkward. Dealing with user input is often awkward.
Later on you will see better ways to do this. Here are some runs of the program:

C:>javac RainTester.java

C:>java RainTester
Is it raining? (Y or N): Y
Wipers On

C:>java RainTester
Is it raining? (Y or N): N
Wipers Off

C:>java RainTester
Is it raining? (Y or N): Yes
Wipers Off

C:>java RainTester
Is it raining? (Y or N): Rats
Wipers Off

QUESTION 4:
Is the integer -12 negative or not?

Number Tester
An integer may be negative, or not. If it is not negative, then it is positive or zero. Here is that idea
expressed as a flow chart:

The diamond box shows a two-way decision. Either the false branch or the true branch is taken depending on
whether

num < 0

is true or false.

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. 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 5:
The user runs the program and enters "12". What will the program print?
The Program
Here is the number tester implemented as a program:

import java.util.Scanner;

class NumberTester
{
public static void main (String[] args)
{
Scanner scan = new Scanner( System.in );
int num;

System.out.println("Enter an integer:");
num = scan.nextInt();

if ( num < 0 )
System.out.println("The number " + num + " is negative");
else
System.out.println("The number " + num + " is zero or positive");

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


}
}
The words if and else are markers that divide the decision into two sections. The else divides the true
branch from the false branch. The if is followed by a question enclosed in parentheses. The expression num
< 0 asks if the value in num is less than zero.
 The if statment always asks a question (often about a variable).
 If the answer is true only the true branch is executed.
 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 6:
The user runs the program and enters -5. What will the program print?
Simulated Program
Here is a simulation of this program (using JavaScript and your browser). Of course, for maximum benefit copy
the program to a file and run it. 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.util.Scanner; Simulated Monitor

class NumberTester
{
public static void main (String[] args)
{
Scanner scan = new Scanner( System.in );
int num;

System.out.println("Enter an integer:");
num = scan.nextInt();

if ( num < 0 )
System.out.println("The number " +
num + " is negative");
else
System.out.println("The number " +
num + " is zero or positive"); 2. Click in the "monitor" window after the
last line and enter a number
System.out.println("Good-bye for now");
}
}

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 7:
Try the program (or look at the flowchart) with the value 0 (zero). What is the output?
More than one Statement per Branch
Here is the program again with some added statements:

import java.util.Scanner;

class NumberTester
{
public static void main (String[] args)
{
Scanner scan = new Scanner( System.in );
int num;

System.out.println("Enter an integer:");
num = scan.nextInt();

if ( num < 0 )
{
System.out.println("The number " + num + " is negative."); // true-branch
System.out.println("Negative numbers are less than zero."); // true-branch
}
else
{
System.out.println("The number " + num +" is zero or positive.");// false-branch
System.out.print ("Positive numbers are greater "); // false-branch
System.out.println("than 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, just block). 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 8:
The user enters a 17. What will the new program print?
Outline of a Two-way Decision
Here is an outline of a two-way decision structure:
// statements that are executed before the decision

if ( condition )
// true branch

else
// false branch

// statements that are executed after the branches join together again
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 statements after the false branch are always 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 9:
Is the following section of a program correct?
if ( num < 0 )
System.out.println("The number " + num + " is negative.");
else
System.out.println("The number " + num + " is zero or positive.");
System.out.print ("Positive numbers are greater ");
System.out.println("than zero. ");

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


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 zero or positive.");
System.out.print ("Positive numbers are greater ");
System.out.println("than zero. ");

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

Our human-friendly indenting shows what we want, but the compiler ignores indenting. The compiler
groups statements according to the braces. What it sees is the same as this:

if ( num < 0 )
System.out.println("The number " + num + " is negative."); // true-
branch
else
System.out.println("The number " + num + " is zero or 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 10:
How would you fix the problem?
Practice
At a movie theater box office a person less than age 13 is charged the "child rate". Otherwise a person
is charged the "adult rate." Here is a partially complete program that does this:

import java.util.Scanner;
class BoxOffice
{
public static void main (String[] args)
{
Scanner scan = new Scanner( System.in );
int age;

System.out.println("Enter your age:");


age = scan.nextInt();

if ( )
{
System.out.println("Child rate.");
}
else
{
System.out.println("Adult rate.");
}
System.out.println("Enjoy the show."); // always executed
}
}

In this program, the true branch and the false branch are both blocks. Each block contains only one statement,
but this is OK. Often programmers do this for clarity.
QUESTION 11:
Fill in the blank so that a person under the age of 13 is charged the child rate.
Box Office Program
Here is the program with the blank filled in correctly:

import java.util.Scanner;
class BoxOffice
{
public static void main (String[] args)
{
Scanner scan = new Scanner( System.in );
int age;

System.out.println("Enter your age:");


age = scan.nextInt();

if ( age < 13 )
{
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 string "21" is converted from characters into an int and put into the variable age.
4. The condition age < 13 is tested.
5. 21 < 13 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 12:
What does the program output if the user enters 11?
Boolean Expressions
We need to look at the condition part of the if statement. Usually this is a boolean expression. Recall that
an expression is is a combination of literals, operators, variable names, and parentheses used to calculate a
value.
A boolean expression is an expression that evaluates to true or false.
Boolean expressions often compare numbers. A relational operator says how the numbers are compared.

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 ?

Here are some annoying details (that will be really annoying 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).
It is easy to forget these two details, and easy to overlook these details in a program. You might spend hours
debugging a program because a = was used where a == belongs.
Using Boolean Expressions

In an if statement, the true or false of a boolean expression picks whether the true branch or the false branch
is executed. Look at another story problem:

A store wants a program that calculates the tax on an item of clothing. An item that costs $100 or more has a 5% tax. An
item that costs less than $100 is tax free. Write a program that asks for a price, then calculates and prints the tax, then
prints the total cost.

Here is the program, not quite finished:


class TaxProgram
{
public static void main (String[] args)
{

double price;
double tax ;

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

if ( )

else

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


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

Here are some program fragments to use in completing the program. Use your mouse to copy-and-paste them
into the program.
tax = price * taxRate; Scanner scan = new Scanner( System.in );
price = scan.nextDouble(); final double taxRate = 0.05;
price >= 100.0 import java.util.Scanner;
tax = 0.0;
(Of course, it would be nice to copy the program to a file, enter your corrections and run the program.)
Adding in a Zero
Here is the complete program.

import java.util.Scanner;
class TaxProgram
{
public static void main (String[] args)
{
final double taxRate = 0.05;
Scanner scan = new Scanner( System.in );
double price;
double tax ;

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


price = scan.nextDouble();

if ( price >= 100.0 )


tax = price * taxRate;
else
tax = 0.0;

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


Total: " + (price+tax) );
}
}
Is the logic of the program is correct? The expression (price+tax) in the last statement sometimes
adds zero to price. This is fine. Adding zero does not change the result.
Three-way Decisions
You might wonder about the restriction that an if statement makes only a two-way decision. Surely you must
sometimes pick from more than just two branches?
We ran into this problem with a previous example program that divided integers into negative and non-negative.
It really should pick one of three choices:
 Negative: ... -3 -2 -1
 Zero: 0
 Positive: +1 +2 +3 ...
Two-way decisions can do this. First divide the integers into two groups (using a two-way decision):
 Negative: ... -3 -2 -1
 Zero and Positive: 0 +1 +2 +3 ...
Then further further divide the second group (by using another two-way decision):
 Negative: ... -3 -2 -1
 Zero and Positive:
o Zero: 0
o Positive: +1 +2 +3 ...
By repeatedly splitting groups into subgroups, you can split a collection into any number of fine divisions.
Flowchart
We wish to perform two splits to divide integers into negative, zero, and positive. First zero and positives
are split from the negatives, and then that group is further split.

The flowchart shows how this works. One decision is nested inside the false branch of the first decision.
A negative integer is correctly sorted out by the first decision. But a zero or positive integer goes through
another decision to pick the correct category for it.
Number Tester Program
Here is a program that implements the flowchart. The part that corresponds to the nested decision of the flow
chart is in red. This is called a nested if statement because it is nested in a branch of an outer if statement.

import java.util.Scanner;

class NumberTester
{
public static void main (String[] args)
{
Scanner scan = new Scanner( System.in );
int num;

System.out.println("Enter an integer:");
num = scan.nextInt();

if ( num < 0 )
{
// true-branch
System.out.println("The number " + num + " is negative");

}
else
{
if ( num > 0 )
{
// nested true-branch
System.out.println("The number " + num + " is positive");
}
else
{
// nested false-branch
System.out.println("The number " + num + " is zero");
}

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


}
}
Chapter 12 Programming Exercises

Code 7 — Pie Eating Contest

At the State Fair Pie Eating Contest all contestants in the heavyweight division must
weigh within 30 pounds of 250 pounds. Write a program that asks for a contestant's
weight and then says if the contestant is allowed in the contest.

Code 8 — Order Checker

Bob's Discount Bolts charges the following prices:

 5 cents per bolt


 3 cents per nut
 1 cent per washer

Write a program that asks the user for the number of bolts, nuts, and washers in their
purchase and then calculates and prints out the total. As an added feature, the program
checks the order. A correct order must have at least as many nuts as bolts and at least
twice as many washers as blots, otherwise the order has an error. For an error the
program writes out "Check the Order: too few nuts" or "Check the Order: too few
washers" as appropriate. Both error messages are written if the order has both errors. If
there are no errors the program writes out "Order is OK." In all cases the total price in
cents (of the specified number of items) is written out.
Number of bolts: 12
Number of nuts: 8
Number of washers: 24

Check the Order: too few nuts

Total cost: 108


Use constants for the unit cost of each item. In other words, declare constants such
as final int boltPrice = 5;.

Code 9 — Last Chance Gas


Al's Last Chance Gas station sits on Route 190 on the edge of Death Valley. There is no
other gas station for 200 miles. You are to write a program to help drivers decide if they
need gas. The program asks for:
 The capacity of the gas tank, in gallons.
 The indication of the gas gauge in percent (full= 100, three quarters full = 75, and so
on).
 The miles per gallon of the car.
The program then writes out "Get Gas" or "Safe to Proceed" depending on if the car can
cross the 200 miles with the gas remaining in the tank.
Tank capacity:
12
Gage reading:
50
Miles per gallon:
30
Get Gas!
Use integers for all input and all arithmetic.

Potrebbero piacerti anche