You learned how to handle multiple actions in a one-way selection structure. Just as there are many situations in which you must perform multiple actions when a decision condi-tion evaluates to true, there are many situacondi-tions in which you must perform two diff erent sets of actions when a decision condition evaluates to true and false, respectively.
For example, a university may place a student in its prestigious dean’s list if the student has 3.75 gpa out of a possible 4.0. If the gpa of a student is greater than or equal to 3.75, the student’s name is entered into dean’s list. However, if the gpa of a student is less than 3.75, university may want to send an encouraging message to the student. In this case, you need a two-way selection structure. Similarly, an automobile insurance fi rm may apply a 20%
discount to drivers with no accident claim in past 3 years. Th is discount applies to drivers with no accident claim in past 3 years. However, as a public relations matter, every customer is given 5% discount. Th is is another situation where a two-way selection is required.
Java provides a control structure if … else to address this issue. Th e syntax of the control structure if … else is as follows:
if (decisionCondition) actionStatementTrue else
actionStatementFalse
Th us, the two-way selection structure if … else has fi ve parts. First, it begins with the reserved word if. Th e second part is a decision condition enclosed within a pair of left and right parentheses. Th e third part is an executable Java statement. Th e fourth is the reserved word else. Th e fi ft h is an executable Java statement. Java treats all fi ve parts together as one Java statement and for the sake of discussion, we call it the if … else statement.
Th e semantics of the if … else statement is as follows. If decision condition evaluates to true, the action statement actionStatementTrue is executed. However, if the decision condition evaluates to false, the action statement actionStatementFalse is executed.
Th e statement immediately following the if … else statement is always executed.
Consider the following:
statementBefore
if (decisionCondition) actionStatementTrue else
actionStatementFalse statementAfter
Apago PDF Enhancer
Th e semantics of the if … else structure can be illustrated through the diagram shown in Figure 4.3. Here, the statementBefore and statementAfter stand for Java statements immediately before and aft er the if … else statement.
As in the case of the if statement, any one or both the action statements can be a block statement.
Example 4.17 Consider the following segment of code:
int ageDifference;
. . .
if (ageDifference <= 20)
System.out.println("are of the same generation");
else
System.out.println("are of different generations");
In the above code, let ageDifference contain the absolute diff erence between ages of two individuals. Th en, if the decision condition (ageDifference <= 20) evaluates to true, then the following message is printed:
They are of the same generation
However, if the expression (ageDifference <= 20) evaluates to false, then the following message is printed:
They are of different generations Let us write a Java program to test our reasoning.
statementBefore
statementAfter
decisionCondition true false
actionStatementTrue actionStatementFalse
FIGURE 4.3 Control structure if … else.
Apago PDF Enhancer
Th e following program reads fi rst names, last names, and ages of two individuals and determines whether or not they are of the same generation. Assume that ageOne and ageTwo are the variables containing the ages of two individuals.
Th en (ageTwo - ageOne) is the diff erence between two age values. However, the above diff erence can be positive or negative. Th erefore, we need to fi nd the absolute value (ageTwo - ageOne). Recall that Java has a static method abs in the Math class. Math.abs(ageTwo - ageOne) computes the absolute diff erence between ageTwo and ageOne.
/**
Example: Two-way selection - same generation
*/
import java.util.Scanner;
public class TwowayAge {
public static void main (String[] args) {
String firstNameOne, lastNameOne;
String firstNameTwo, lastNameTwo;
int ageOne, ageTwo, ageDifference;
Scanner scannedInfo = new Scanner(System.in);
System.out.print
("Enter first name, last name and age : ");
System.out.flush();
firstNameOne = scannedInfo.next();
lastNameOne = scannedInfo.next();
ageOne = scannedInfo.nextInt();
System.out.println();
System.out.print
("Enter first name, last name and age : ");
System.out.flush();
firstNameTwo = scannedInfo.next();
lastNameTwo = scannedInfo.next();
ageTwo = scannedInfo.nextInt();
System.out.println();
ageDifference = Math.abs(ageTwo - ageOne);
System.out.print(firstNameOne + " " + lastNameOne + " and " + firstNameTwo + " " + lastNameTwo + " " );
Apago PDF Enhancer
if (ageDifference <= 20)
System.out.println("are of the same generation.");
else
System.out.println("are of different generations.");
} }
Output Case 1: ageOne < ageTwo, same generation
Enter first name, last name and age : Joy Mathew 37 Enter first name, last name and age : Chris Cox 57 Joy Mathew and Chris Cox are of the same generation.
Case 2: ageOne > ageTwo, diff erent generation
Enter first name, last name and age : Adam Smith 67 Enter first name, last name and age : Mike McCoy 46 Adam Smith and Mike McCoy are of different generations
Example 4.18
In this example, we use the String method compareTo. Th is example also illustrates the use of block statements in an if … else statement.
Let us call the name of a person ascending if the last name is lexicographically larger than the fi rst name. Th is example verifi es whether or not a person’s name is ascend-ing. Recall that to compare two strings, you use compareTo method of the String class and if strOne and strTwo are two strings, strOne.compareTo(strTwo) returns a negative value if strOne is smaller than strTwo. Th erefore, if first-Name and lastName are String variables for fi rst name and last name of a person, firstName.compareTo(lastName) is less than 0 if the name of the person is an ascending name. In other words, (firstName.compareTo(lastName) < 0) is true for ascending names. Th e complete program is as follows:
/**
Example: Two-way selection – Ascending Name
*/
import java.util.Scanner;
public class AscendingName {
public static void main (String[] args) {
String firstName, lastName;
Apago PDF Enhancer
Scanner scannedInfo = new Scanner(System.in);
System.out.print
("Enter first name, last name: ");
System.out.flush();
firstName = scannedInfo.next();
lastName = scannedInfo.next();
System.out.println();
if (firstName.compareTo(lastName) < 0) {
System.out.println("Hi " + firstName + " " + lastName);
System.out.println
("You got an ascending Name!");
} else {
System.out.println("Sorry! " + firstName + " " + lastName);
System.out.println
("Your name is not an ascending one!");
} } }
Output Case 1: Ascending name
Enter first name, last name: James Jones Hi James Jones
You got an ascending Name!
Case 2: Not an ascending name
Enter first name, last name: Elaine Cox Sorry! Elaine Cox
Your name is not an ascending one!
Self-Check
21. Write the code to print “Set for life!” if the net worth is more than $10 million dol-lars and print “Not there yet!” otherwise.
22. Write the code to print “Expensive item” if the cost is more than $25.00 and print “Reasonable Item” otherwise.