CS 1063  Week 9:  Decisions

Objectives

Assignments



Boolean expressions with relational operators

A boolean expression is one that has a value that is either true or false.  Use a boolean variable to hold the value of a boolean expression.

A relational operator is one that compares two values.  (In contrast to an arithmetic operator that combines two values to produce a new arithmetic value.)

Relational operators
Symbol Meaning Example
==
equal to if ( a == 5 )
>
greater than if ( salary > 30000 )
<
less than if ( 0 < salary )
!=
not equal to if ( a != b )
>=
greater than or equal to if ( salary >= 10000 )
<=
less than or equal to if ( 20000 <= salary )

The if and if/else statements

The if statement lets a program carry out different actions depending on the outcome of a condition.

One consequent:

if ( condition )
   truestatement;

Two alternatives:

if ( condition )
   truestatement;
else
   falsestatement;

Examples of using an if statement:

if ( numGrades != 0 ) 
   average = sum/numGrades; 

if ( amount <= balance )
   balance = balance - amount;

Examples of using the if/else statement:

if ( value >= 0 )
   System.out.println("square root of " + value + " = " +  Math.sqrt(value));
else
   System.out.println("negative number " + value + " entered");

if ( amount <= balance )
   balance = balance - amount;
else
   balance = balance - OVERDRAFT_PENALTY;
A block statement groups several statements together.

Example: What does the following do? (Trace with variables)

if ( x > y ) {
   temp = x;
   x = y;
   y = temp;
}

In the above example more than one statement is included in the consequent, so we use curly braces ({ }) to group them.

Activity 1

Activity 2  The QuadraticEquation Class

Write a program that prints all real solutions to the quadratic equation ax2 + bx + c = 0.  Read in a, b, and c and use the quadratic formula.  If the discriminant b2 - 4ac is negative, display a message stating that there are no real solutions.  Implement the class QuadraticEquation whose constructor receives the coefficients a, b, and c of the quadratic equation.  Supply methods calculateSolution1 and calculateSolution2 that get the solutions using the quadratic formula.  Supply a method boolean hasSolution() that returns false if the discriminant is negative and true otherwise.

Setup:

Test your class by asking the user to enter values for a, b and c.  Remember that you must use hasSolution before you call calculateSolution1 and calculateSolution2.  Find 3 values that produce the message no real solution and 3 values that have a solution.

Multiple-alternative decision

Multiple conditions can be combined to evaluate complex decisions.
The correct arrangement depends on the logic of the problem to be solved.
System.out.println("Score is " + score);
if ( score >= 90 )
   System.out.println("Grade is A");
else if ( score >= 80 )
   System.out.println("Grade is B");
else if ( score >= 70 )
   System.out.println("Grade is C"); 
else if ( score >= 60 ) 
   System.out.println("Grade is D");
else
   System.out.println("Grade is F");

Nested selection statements in the if clause

Nested selection occurs when the either the true clause or the false clause are themselves an if statement.  When the nesting occurs in the if, the code can be very confusing.  What happens in the following when x has value 5 and y has value 2?

if ( x >= 0 )
   if ( y >= x )
      System.out.println(" y >= x >= 0 ");
else
   System.out.println(" x < 0 ");

Answer: Probably not what you think.  The Java rule for matching else with if is that Java matches each else with the closest preceding if that is not matched with a closer else.  (It doesn't matter how YOU indent.)

A corrected version using { }:

if ( x >= 0 ) {
   if ( y >= x )
      System.out.println(" y >= x >= 0 ");
}
else
   System.out.println(" x < 0 ");
Hint:  Try to avoid the nesting of selection in the if clause, it is almost always hard to figure out.  Instead, reorganize your code or use boolean operators to combine conditions.

Activity 3

Activity 4  The Earthquake Class

Write a program that asks for a value describing the magnitude of an earthquake on the Richter scale and prints a description of the likely impact of the quake.  The Richter scale is a measurement for the strength of an earthquake.  Every step in the scale, for example from 6.0 to 7.0, signifies a tenfold increase in the strength of the quake.  Use the following:

if the richter is >= 8.0 output "Most structures fall"
if the richter is >= 7.0 and < 8.0 output "Many buildings destroyed"
if the richter is >= 6.0 and < 7.0 output " Many buildings considerably damaged; some collapse"
if the richter is >= 4.5 and < 6.0 output "Damage to poorly constructed buildings"
if the richter is >= 3.5 and < 4.5 output "Felt by many people, no destruction"
if the richter is >= 0 and < 3.5 output "Generally not felt by people"
if the richter is < 0 output "Negative numbers are not valid"

This solution should use a multiple-alternative decision without the and / or operators.  For this solution write an Earthquake class with a constructor that takes the magnitude of the earth quake and a method that calculates and returns the description of the effect as a String.  Provide a method setMagnitude(double magnitude) that replaces the current magnitude with a new one.  Use the following data that tests your branches.

Instantiate an Earthquake object e with a magnitude of 9.0
Output the effect
set the magnitude at 8.0
Output the effect
set the magnitude at 7.5
Output the effect
set the magnitude at 7.0
Output the effect
set the magnitude at 6.5
Output the effect
set the magnitude at 6.0
Output the effect
set the magnitude at 5.0
Output the effect
set the magnitude at 4.5
Output the effect
set the magnitude at 4.0
Output the effect
set the magnitude at 3.5
Output the effect
set the magnitude at 2.0
Output the effect
set the magnitude at 0.0
Output the effect
set the magnitude at -1.0