Big Java 5

Chapter 5 – Decisions

Chapter Goals

train switching

The if Statement

elevator panel

This elevator panel “skips” the thirteenth floor. The floor is not actually missing—the computer that controls the elevator adjusts the floor numbers above 13.

int actualFloor;
if (floor > 13)
{
   actualFloor = floor - 1;
}
else
{
   actualFloor = floor;
}

The if Statement

The if Statement

The if Statement

fork in the road

An if statement is like a fork in the road. Depending upon a decision, different parts of the program are executed.

Syntax 5.1 The if Statement

if syntax

section_1/ElevatorSimulation.java

Your browser does not support this feature Program Run:

Self Check 5.1

In some Asian countries, the number 14 is considered unlucky. Some building owners play it safe and skip both the thirteenth and the fourteenth floor. How would you modify the sample program to handle such a building?

Self Check 5.2

Consider the following if statement to compute a discounted price:
if (originalPrice > 100)
{
   discountedPrice = originalPrice - 20;
}
else
{
   discountedPrice = originalPrice - 10;
}
What is the discounted price if the original price is 95? 100? 105?

Self Check 5.3

Compare this if statement with the one in Self Check 2:
if (originalPrice < 100)
{
   discountedPrice = originalPrice - 10;
}
else
{
   discountedPrice = originalPrice - 20;
}
Do the two statements always compute the same value? If not, when do the values differ?

Self Check 5.4

Consider the following statements to compute a discounted price:
discountedPrice = originalPrice;
if (originalPrice > 100)
{
   discountedPrice = originalPrice - 10;
}
What is the discounted price if the original price is 95? 100? 105?

Self Check 5.5

The variables fuelAmount and fuelCapacity hold the actual amount of fuel and the size of the fuel tank of a vehicle. If less than 10 percent is remaining in the tank, a status light should show a red color; otherwise it shows a green color. Simulate this process by printing out either "red" or "green".

Avoid Duplication in Branches

Avoid Duplication in Branches (continued)

Comparing Values: Relational Operators

Justice's balance scale

In Java, you use a relational operator to check whether one value is greater than another.

Comparing Values: Relational Operators

Syntax 5.2 Comparisons

syntax for comparisons

Comparing Floating-Point Numbers

Comparing Floating-Point Numbers

Comparing Strings

Comparing Strings - compareTo method

Lexicographic Ordering

Comparing Objects

Object Comparison

Rectangle references

Testing for null

Relational Operator Examples

relational operators

Self Check 5.6

Which of the following conditions are true, provided a is 3 and b is 4?
a. a + 1 <= b
b. a + 1 >= b
c. a + 1 != b

Self Check 5.7

Give the opposite of the condition floor > 13

Self Check 5.8

What is the error in this statement?
if (scoreA = scoreB)
{
   System.out.println("Tie");
}

Self Check 5.9

Supply a condition in this if statement to test whether the user entered a Y:
System.out.println("Enter Y to quit.");
String input = in.next();
if (. . .)
{
   System.out.println("Goodbye.");
}

Self Check 5.10

Give two ways of testing that a string str is the empty string.

Self Check 5.11

What is the value of s.length() if s is

a. the empty string ""?
b. the string " " containing a space?
c. null?

Self Check 5.12

Which of the following comparisons are syntactically incorrect? Which of them are syntactically correct, but logically questionable?
String a = "1";
String b = "one";
double x = 1;
double y = 3 * (1.0 / 3);
a. a == "1"
b. a == null
c. a.equals("")
d. a == b
e. a == x
f. x == y
g. x - y == null
h. x.equals(y)

Multiple Alternatives: Sequences of Comparisons

Multiple Alternatives

earthquake_damage

The 1989 Loma Prieta earthquake that damaged the Bay Bridge in San Francisco and destroyed many buildings measured 7.1 on the Richter scale.

richter scale

Multiple Alternatives - Flowchart

flowchart of multiple alternatives

Multiple Alternatives

Multiple Alternatives

Self Check 5.13

In a game program, the scores of players A and B are stored in variables scoreA and scoreB. Assuming that the player with the larger score wins, write an if/ else if/else sequence that prints out "A won", "B won", or "Game tied".

Self Check 5.14

Write a conditional statement with three branches that sets s to 1 if x is positive, to –1 if x is negative, and to 0 if x is zero.

Self Check 5.15

How could you achieve the task of Self Check 14 with only two branches?

Self Check 5.16

Beginners sometimes write statements such as the following:
if (price > 100)
{
   discountedPrice = price - 20;
}
else if (price <= 100)
{
   discountedPrice = price - 10;
}
Explain how this code can be improved.

Self Check 5.17

Suppose the user enters -1 into the earthquake program. What is printed?

Self Check 5.18

Suppose we want to have the earthquake program check whether the user entered a negative number. What branch would you add to the if statement, and where?

Nested Branches

Nested Branches - Flowchart

Income tax flowchart

section_4/TaxReturn.java

Your browser does not support this feature

section_4/TaxCalculator.java

Your browser does not support this feature Program Run:

Self Check 5.19

What is the amount of tax that a single taxpayer pays on an income of $32,000?

Self Check 5.20

Would that amount change if the first nested if statement changed from
if (income <= RATE1_SINGLE_LIMIT) 
to
if (income < RATE1_SINGLE_LIMIT)

Self Check 5.21

Suppose Harry and Sally each make $40,000 per year. Would they save taxes if they married?

Self Check 5.22

How would you modify the TaxCalculator.java program in order to check that
the user entered a correct value for the marital status (i.e., Y or N)?

Self Check 5.23

Some people object to higher tax rates for higher incomes, claiming that you might end up with less money after taxes when you get a raise for working hard. What is the flaw in this argument?

Problem Solving: Flowcharts

Problem Solving: Flowcharts

Problem Solving: Flowcharts

Problem Solving: Flowcharts

Self Check 5.24

Draw a flowchart for a program that reads a value temp and prints “Frozen” if it is less than zero.

Self Check 5.25

What is wrong with this flowchart?

flowcahart for self-check question 5.25

Self Check 5.26

How do you fix the flowchart of Self Check 25?

Self Check 5.27

Draw a flowchart for a program that reads a value x. If it is less than zero, print “Error”. Otherwise, print its square root.

Self Check 5.28

Draw a flowchart for a program that reads a value temp. If it is less than zero, print “Ice”. If it is greater than 100, print “Steam”. Otherwise, print “Liquid”.

Problem Solving: Selecting Test Cases

Problem Solving: Selecting Test Cases

Self Check 5.29

Using Figure 1 on page 181 as a guide, follow the process described in this section to design a set of test cases for the ElevatorSimulation.java program in Section 5.1.

Self Check 5.30

What is a boundary test case for the algorithm in How To 5.1 on page 193? What is the expected output?

Self Check 5.31

Using Figure 4 on page 197 as a guide, follow the process described in Section 5.6 to design a set of test cases for the Earthquake.java program in Section 5.3.

Self Check 5.32

Suppose you are designing a part of a program for a medical robot that has a sensor returning an x- and y-location (measured in cm). You need to check whether the sensor location is inside the circle, outside the circle, or on the boundary (specifically, having a distance of less than 1 mm from the boundary). Assume the circle has center (0, 0) and a radius of 2 cm. Give a set of test cases.
2 cm circle

Boolean Variables and Operators

Boolean Variables and Operators

Boolean Variables and Operators

Boolean Variables and Operators

Boolean Variables and Operators

Boolean operator examples

Boolean Variables and Operators

Self Check 5.33

Suppose x and y are two integers. How do you test whether both of them are zero?

Self Check 5.34

How do you test whether at least one of them is zero?

Self Check 5.35

How do you test whether exactly one of them is zero?

Self Check 5.36

What is the value of !!frozen?

Self Check 5.37

What is the advantage of using the type boolean rather than strings "false"/"true" or integers 0/1?

Application: Input Validation

Section_8/ElevatorSimulation2.java

Your browser does not support this feature Program Run:

Self Check 5.38

In the ElevatorSimulation2 program, what is the output when the input is
a. 100?
b. –1?
c. 20?
d. thirteen?

Self Check 5.39

Your task is to rewrite lines 19–26 of the ElevatorSimulation2 program so that there is a single if statement with a complex condition. What is the condition?
if (. . .)
{
   System.out.println("Error: Invalid floor number");
}

Self Check 5.40

In the Sherlock Holmes story “The Adventure of the Sussex Vampire”, the inimitable detective uttered these words: “Matilda Briggs was not the name of a young woman, Watson, … It was a ship which is associated with the giant rat of Sumatra, a story for which the world is not yet prepared.” Over a hundred years later, researchers found giant rats in Western New Guinea, another part of Indonesia. Suppose you are charged with writing a program that processes rat weights. It contains the statements
System.out.print("Enter weight in kg: ");
double weight = in.nextDouble();
What input checks should you supply?

Self Check 5.41

Run the following test program and supply inputs 2 and three at the prompts. What happens? Why?
import java.util.Scanner
public class Test
{
   public static void main(String[] args)
   {
      Scanner in = new Scanner(System.in);
      System.out.print("Enter an integer: ");
      int m = in.nextInt();
      System.out.print("Enter another integer: ");
      int n = in.nextInt();
      System.out.println(m + " " + n);
   }
}