Using Conditional Tests to Make Decisions - Learning the Basics of Programming - Sams Teach Yourself Java in 24 Hours, 7th Edition (2014)

Sams Teach Yourself Java in 24 Hours, 7th Edition (2014)

Part II: Learning the Basics of Programming

Hour 7. Using Conditional Tests to Make Decisions

THIS HOUR’S TO-DO LIST:

Image Use the if statement for basic conditional tests.

Image Test whether one value is greater than or less than another.

Image Test whether two values are equal or unequal.

Image Use else statements as the opposite of if statements.

Image Chain several conditional tests together.

Image Use the switch statement for complicated conditional tests.

Image Create tests with the ternary operator.

When you write a computer program, you provide the computer with a list of instructions called statements, and these instructions are followed to the letter. You can tell the computer to work out some unpleasant mathematical formulas, and it works them out. Tell it to display some information, and it dutifully responds.

There are times when you need the computer to be more selective about what it does. For example, if you have written a program to balance your checkbook, you might want the computer to display a warning message if your account is overdrawn. The computer should display this message only if your account is overdrawn. If it isn’t, the message would be inaccurate and emotionally upsetting.

The way to accomplish this task in a Java program is to use a conditional, a statement that causes something to happen in a program only if a specific condition is met. During this hour, you learn how to use the conditionals if, else, and switch.

When a Java program makes a decision, it does so by employing a conditional statement. During this hour, you are checking the condition of several things in your Java programs using the conditional keywords if, else, switch, case, and break. You also use the conditional operators==, !=, <, >, <=, >=, and ?, along with boolean variables.

if Statements

The most basic way to test a condition in Java is by using an if statement. The if statement tests whether a condition is true or false and takes action only if the condition is true.

You use if along with the condition to test, as in the following statement:

long account = -17_000_000_000_000L;
if (account < 0) {
System.out.println("Account overdrawn; you need a bailout");
}

The if statement checks whether the account variable is below 0 by using the less-than operator <. If it is, the block within the if statement is run, displaying text.

The block runs only if the condition is true. In the preceding example, if the account variable has a value of 0 or higher, the println statement is ignored. Note that the condition you test must be surrounded by parentheses, as in (account < 0).

The less-than operator < is one of several operators you can use with conditional statements.

Less-Than and Greater-Than Comparisons

In the preceding section, the < operator is used the same way as in math class: as a less-than sign. There also is a greater-than conditional operator >, which is used in the following statements:

int elephantWeight = 900;
int elephantTotal = 13;
int cleaningExpense = 200;

if (elephantWeight > 780) {
System.out.println("Elephant too big for tightrope act");
}

if (elephantTotal > 12) {
cleaningExpense = cleaningExpense + 150;
}

The first if statement tests whether the value of the elephantWeight variable is greater than 780. The second if statement tests whether the elephantTotal variable is greater than 12.

If the two preceding statements are used in a program where elephantWeight is equal to 600 and elephantTotal is equal to 10, the statements within each if block are ignored.

You can determine whether something is less than or equal to something else with the <= operator. Here’s an example:

if (account <= 0) {
System.out.println("You are flat broke");
}

There’s also a >= operator for greater-than-or-equal-to tests.

Equal and Not Equal Comparisons

Another condition to check in a program is equality. Is a variable equal to a specific value? Is one variable equal to the value of another? These questions can be answered with the == operator, as in the following statements:

if (answer == rightAnswer) {
studentGrade = studentGrade + 10;
}

if (studentGrade == 100) {
System.out.println("Show off!");
}

You also can test inequality, whether something is not equal to something else, with the != operator, as follows:

if (answer != rightAnswer) {
score = score - 5;
}


Caution

The operator used to conduct equality tests has two equal signs: ==. It’s easy to confuse this operator with the = operator, which is used to give a value to a variable. Always use two equal signs in a conditional statement.


You can use the == and != operators with every type of variable except for strings, because strings are objects.

Organizing a Program with Block Statements

Up to this point, the if statements in this hour have been accompanied by a block contained within { and } brackets. (I believe the technical term for these characters is “squiggly bracket marks.”)

Previously, you have seen how block statements are used to mark the beginning and end of the main() block of a Java program. Each statement within the main() block is handled when the program is run.

An if statement does not require a block statement. It can occupy a single line, as in this example:

if (account <= 0) System.out.println("No more money");

The statement that follows the if conditional is executed only if the condition is true.

Listing 7.1 is an example of a Java program with a block statement used to denote the main() block. The block statement begins with the opening bracket { on Line 3 and ends with the closing bracket } on Line 15. Create a new empty Java file called Game in NetBeans in thecom.java24hours package and enter the text in Listing 7.1.

LISTING 7.1 The Game Program


1: package com.java24hours;
2:
3: class Game {
4: public static void main(String[] arguments) {
5: int total = 0;
6: int score = 7;
7: if (score == 7) {
8: System.out.println("You score a touchdown!");
9: }
10: if (score == 3) {
11: System.out.println("You kick a field goal!");
12: }
13: total = total + score;
14: System.out.println("Total score: " + total);
15: }
16: }


When you run the program, the output should resemble Figure 7.1.

Image

FIGURE 7.1 The output of the Game program.

You can use block statements in if statements to make the computer do more than one thing if a condition is true. The following is an example of an if statement that includes a block statement:

int playerScore = 12000;
int playerLives = 3;
int difficultyLevel = 10;

if (playerScore > 9999) {
playerLives++;
System.out.println("Extra life!");
difficultyLevel = difficultyLevel + 5;
}

The brackets are used to group all statements that are part of the if statement. If the variable playerScore is greater than 9,999, three things happen:

Image The value of the playerLives variable increases by 1 (because the increment operator ++ is used).

Image The text “Extra life!” is displayed.

Image The value of the difficultyLevel variable is increased by 5.

If the variable playerScore is not greater than 9,999, nothing happens. All three statements inside the if statement block are ignored.

if-else Statements

There are times when you want to do something if a condition is true and something else if the condition is false. You can do this by using the else statement in addition to the if statement, as in the following example:

int answer = 17;
int correctAnswer = 13;

if (answer == correctAnswer) {
score += 10;
System.out.println("That's right. You get 10 points");
} else {
score -= 5;
System.out.println("Sorry, that's wrong. You lose 5 points");
}

The else statement does not have a condition listed alongside it, unlike the if statement. The else statement is matched with the if statement that immediately precedes it. You also can use else to chain several if statements together, as in the following example:

if (grade == 'A') {
System.out.println("You got an A. Awesome!");
} else if (grade == 'B') {
System.out.println("You got a B. Beautiful!");
} else if (grade == 'C') {
System.out.println("You got a C. Concerning!");
} else {
System.out.println("You got an F. You'll do well in Congress!");
}

By putting together several if and else statements in this way, you can handle a variety of conditions. The preceding example sends a specific message to A students, B students, C students, and future legislators.

switch Statements

The if and else statements are good for situations with two possible conditions, but there are times when you have more than two conditions.

With the preceding grade example, you saw that if and else statements can be chained to handle several different conditions.

Another way to do this is with the switch statement, which can test for a variety of different conditions and respond accordingly. In the following code, the grading example has been rewritten with a switch statement:

switch (grade) {
case 'A':
System.out.println("You got an A. Awesome!");
break;
case 'B':
System.out.println("You got a B. Beautiful!");
break;
case 'C':
System.out.println("You got a C. Concerning!");
break;
default:
System.out.println("You got an F. You'll do well in Congress!");
}

The first line of the switch statement specifies the variable that is tested—in this example, grade. Then, the switch statement uses the { and } brackets to form a block statement.

Each case statement checks the test variable in the switch statement against a specific value. The value used in a case statement can be a character, an integer, or a string. In the preceding example, there are case statements for the characters A, B, and C. Each has one or two statements that follow it. When one of these case statements matches the variable in switch, the computer handles the statements after the case statement until it encounters a break statement.

For example, if the grade variable has the value of B, the text “You got a B. Good work!” is displayed. The next statement is break, so nothing else in the switch statement is executed. The break statement tells the computer to break out of the switch statement.

Forgetting to use break statements in a switch statement can lead to undesired results. If there were no break statements in this grading example, the first three “You got a” messages would be displayed whether the grade variable equals ‘A’, ‘B’, or ‘C’.

The default statement is used as a catch-all if none of the preceding case statements is true. In this example, it occurs if the grade variable does not equal A, B, or C. You do not have to use a default statement with every switch block statement you use in your programs. If it is omitted, nothing happens if none of the case statements has the correct value.

The Commodity class in Listing 7.2 uses switch to either buy or sell an unspecified commodity. The commodity costs $20 when purchased and earns $15 when sold.

A switch-case statement tests the value of a string named command, running one block if it equals “BUY” and another if it equals “SELL”.

LISTING 7.2 The Commodity Program


1: package com.java24hours;
2:
3: class Commodity {
4: public static void main(String[] arguments) {
5: String command = "BUY";
6: int balance = 550;
7: int quantity = 42;
8:
9: switch (command) {
10: case "BUY":
11: quantity += 5;
12: balance -= 20;
13: break;
14: case "SELL":
15: quantity -= 5;
16: balance += 15;
17: }
18: System.out.println("Balance: " + balance + "\n"
19: + "Quantity: " + quantity);
20: }
21: }


This application sets the command string to “BUY” in line 5. When the switch is tested, the case block in lines 11–13 is run. The quantity of the commodity increases by 5 and the balance is lowered by $20.

When the Commodity program is run, it produces the output shown in Figure 7.2.

Image

FIGURE 7.2 The output of the Commodity program.

The Ternary Operator

The most complicated conditional statement in Java is the ternary operator ?.

You can use the ternary operator when you want to assign a value or display a value based on a condition. For example, consider a video game that sets the numberOfEnemies variable based on whether the skillLevel variable is greater than 5. One way you can do this is an if-elsestatement:

if (skillLevel > 5) {
numberOfEnemies = 20;
} else {
numberOfEnemies = 10;
}

A shorter way to do this is to use the ternary operator. A ternary expression has five parts:

Image The condition to test, surrounded by parentheses, as in (skillLevel > 5)

Image A question mark (?)

Image The value to use if the condition is true

Image A colon (:)

Image The value to use if the condition is false

To use the ternary operator to set numberOfEnemies based on skillLevel, you could use the following statement:

int numberOfEnemies = (skillLevel > 5) ? 20 : 10;

You also can use the ternary operator to determine what information to display. Consider the example of a program that displays the text “Mr.” or “Ms.” depending on the value of the gender variable. Here’s a statement that accomplishes this:

System.out.print( (gender.equals("male")) ? "Mr." : "Ms." );

The ternary operator can be useful, but it’s also the hardest conditional in Java to understand. As you learn Java, you don’t encounter any situations where the ternary operator must be used instead of if-else statements.

Watching the Clock

This hour’s final project gives you another look at each of the conditional tests you can use in your programs. For this project, you use Java’s built-in timekeeping feature, which keeps track of the current date and time, and present this information in sentence form.

Load NetBeans or another development tool you’re using to create Java programs, and give a new document the name Clock.java and package com.java24hours. This program is long, but most of it consists of multiline conditional statements. Type the full text of Listing 7.3 into the editor and save the file as Clock.java when you’re done.

LISTING 7.3 The Clock Program


1: package com.java24hours;
2:
3: import java.time.*;
4: import java.time.temporal.*;
5:
6: class Clock {
7: public static void main(String[] arguments) {
8: // get current time and date
9: LocalDateTime now = LocalDateTime.now();
10: int hour = now.get(ChronoField.HOUR_OF_DAY);
11: int minute = now.get(ChronoField.MINUTE_OF_HOUR);
12: int month = now.get(ChronoField.MONTH_OF_YEAR);
13: int day = now.get(ChronoField.DAY_OF_MONTH);
14: int year = now.get(ChronoField.YEAR);
15:
16: // display greeting
17: if (hour < 12) {
18: System.out.println("Good morning.\n");
19: } else if (hour < 17) {
20: System.out.println("Good afternoon.\n");
21: } else {
22: System.out.println("Good evening.\n");
23: }
24:
25: // begin time message by showing the minutes
26: System.out.print("It's");
27: if (minute != 0) {
28: System.out.print(" " + minute + " ");
29: System.out.print( (minute != 1) ? "minutes" :
30: "minute");
31: System.out.print(" past");
32: }
33:
34: // display the hour
35: System.out.print(" ");
36: System.out.print( (hour > 12) ? (hour - 12) : hour );
37: System.out.print(" o'clock on ");
38:
39: // display the name of the month
40: switch (month) {
41: case 1:
42: System.out.print("January");
43: break;
44: case 2:
45: System.out.print("February");
46: break;
47: case 3:
48: System.out.print("March");
49: break;
50: case 4:
51: System.out.print("April");
52: break;
53: case 5:
54: System.out.print("May");
55: break;
56: case 6:
57: System.out.print("June");
58: break;
59: case 7:
60: System.out.print("July");
61: break;
62: case 8:
63: System.out.print("August");
64: break;
65: case 9:
66: System.out.print("September");
67: break;
68: case 10:
69: System.out.print("October");
70: break;
71: case 11:
72: System.out.print("November");
73: break;
74: case 12:
75: System.out.print("December");
76: }
77:
78: // display the date and year
79: System.out.println(" " + day + ", " + year + ".");
80: }
81: }



Caution

Because this program uses new features of Java 8, it won’t compile if the current NetBeans project is set to use an earlier version of the language. To make sure the correct setting has been chosen, choose File, Project Properties. In the Project Properties dialog, look for the Source/Binary Format value. It should be JDK 8.


After the program is saved, look it over to get a good idea about how the conditional tests are being used.

With the exception of Lines 3–4 and Lines 8–14, the Clock program contains material that has been covered up to this point. After a series of variables are set up to hold the current date and time, a series of if or switch conditionals are used to determine what information should be displayed.

This program contains several uses of System.out.println() and System.out.print() to display strings.

Lines 8–14 refer to a LocalDateTime variable called now. The LocalDateTime variable type is capitalized because LocalDateTime is an object.

You learn how to create and work with objects during Hour 10, “Creating Your First Object.” For this hour, focus on what’s taking place in those lines rather than how it’s happening.

The Clock program is made up of the following sections:

Image Line 3 enables your program to use a class that is needed to track the current date and time: java.time.LocalDateTime.

Image Line 4 enables the program to use the class java.time.temporalfield.ChronoField, which sounds like something from a time travel movie.

Image Lines 6–7 begin the Clock program and its main() statement block.

Image Line 9 creates a LocalDateTime object called now that contains the current date and time of your system. The now object changes each time you run this program. (Unless the physical laws of the universe are altered and time stands still.)

Image Lines 10–14 create variables to hold the hour, minute, month, day, and year. The values for these variables are pulled from the LocalDateTime object, which is the storehouse for all this information. The information within the parentheses, such asChronoField.DAY_OF_MONTH, indicates which part of the date and time to pull.

Image Lines 17–23 display one of three possible greetings: “Good morning.”, “Good afternoon.”, or “Good evening.” The greeting to display is selected based on the value of the hour variable.

Image Lines 26–32 display the current minute along with some accompanying text. First, the text “It’s” is displayed in Line 26. If the value of minute is equal to 0, Lines 28–31 are ignored because of the if statement in Line 27. This statement is necessary because it would not make sense for the program to tell someone that it’s 0 minutes past an hour. Line 28 displays the current value of the minute variable. A ternary operator is used in Lines 29–30 to display either the text “minutes” or “minute,” depending on whether minute is equal to 1. Finally, in Line 31 the text “past” is displayed.

Image Lines 35–37 display the current hour by using another ternary operator. This ternary conditional statement in Line 36 causes the hour to be displayed differently if it is larger than 12, which prevents the computer from stating times like “15 o’clock.”

Image Lines 40–76, almost half of the program, are a long switch statement that displays a different name of the month based on the integer value stored in the month variable.


Note

The Clock application uses the new Date/Time API introduced in Java 8. Earlier versions of Java used a different set of classes to work with dates and times. As you may recall from Hour 4, “Understanding How Java Programs Work,” the Java Class Library includes thousands of classes that perform useful tasks. The java.time and java.time.temporal packages used in this program are part of the Date/Time API.


Image Line 79 finishes off the display by showing the current date and the year.

Image Lines 80–81 close out the main() statement block and then the entire Clock program.

When you run this program, the output should display a sentence based on the current date and time. The output of the application is shown in the Output pane in Figure 7.3.

Image

FIGURE 7.3 The output of the Clock program.

Run the program several times to see how it keeps up with the clock.

Summary

Now that you can use conditional statements, the overall intelligence of your Java programs has improved greatly. Your programs can evaluate information and use it to react differently in different situations, even if information changes as the program is running. They can decide between two or more alternatives based on specific conditions.

Programming a computer forces you to break a task down into a logical set of steps to undertake and decisions that must be made. Using the if statement and other conditionals in programming also promotes a type of logical thinking that can reap benefits in other aspects of your life:

ImageIf that candidate is elected president in November, I will seek a Cabinet position, else I will move to Canada.”

ImageIf my blind date likes me, I’ll pay for dinner at an expensive restaurant, else we will go to Pizza Hut.”

ImageIf I violate my probation, the only team that will draft me is the Oakland Raiders.”

Workshop

Q&A

Q. The if statement seems like the one that’s most useful. Is it possible to use only if statements in programs and never use the others?

A. It’s possible to do without else or switch, and many programmers never use the ternary operator ?. However, else and switch often are beneficial to use in your programs because they make the programs easier to understand. A set of if statements chained together can become unwieldy.

Q. During this hour, opening and closing brackets { and } sometimes are not used with an if statement if it is used in conjunction with only one statement. Isn’t it mandatory to use brackets?

A. No. Brackets can be used as part of any if statement to surround the part of the program that’s dependent on the conditional test. Using brackets is a good practice to get into because it prevents a common error that might take place when you revise the program. If you add a second statement after an if conditional and don’t add brackets, unexpected errors occur when the program is run.

Q. Does break have to be used in each section of statements that follow a case?

A. You don’t have to use break. If you do not use it at the end of a group of statements, all the remaining statements inside the switch block statement are handled, regardless of the case value they are being tested with.

However, in most cases you’re likely to want a break statement at the end of each group.

Q. Why did the Thompson Twins get that name when they were a trio, were not related, and none of them was named Thompson?

A. Band members Tom Bailey, Alannah Currie, and Joe Leeway called themselves the Thompson Twins in honor of Thomson and Thompson, a pair of bumbling detectives featured in the Belgian comic books The Adventures of Tintin.

The bowler-wearing detectives were physically indistinguishable except for a minor difference in the shape of their mustaches. Despite being terrible at their jobs, they were inexplicably assigned to important and sensitive missions. They often pursued Tintin for crimes that he did not commit.

As their names would indicate, the detectives were not related either.

Quiz

The following questions see what condition you’re in after studying conditional statements in Java.

1. Conditional tests result in either a true or false value. Which variable type does this remind you of?

A. None. Stop pestering me with all these questions.

B. The long variable type.

C. The boolean type.

2. Which statement is used as a catch-all category in a switch block statement?

A. default

B. otherwise

C. onTheOtherHand

3. What’s a conditional?

A. The thing that repairs messy split ends and tangles after you shampoo.

B. Something in a program that tests whether a condition is true or false.

C. The place where you confess your sins to a religious authority figure.

Answers

1. C. The boolean variable type only can equal true or false, making it similar to conditional tests. If you answered A., I’m sorry, but there are only 17 hours left and we’ve got a lot left to cover. Java doesn’t teach itself.

2. A. default statements are handled if none of the other case statements matches the switch variable.

3. B. The other answers describe conditioner and a confessional.

Activities

To improve your conditioning in terms of Java conditionals, review the topics of this hour with the following activities:

Image Add “//” in front of a break statement on one of the lines in the Clock program to make it a comment; then compile it and see what happens when you run it. Try it again with a few more break statements removed.

Image Create a short program that stores a value of your choosing from 1 to 100 in an integer variable called grade. Use this grade variable with a conditional statement to display a different message for all A, B, C, D, and F students. Try it first with an if statement, and then try it with aswitch statement.

To see Java programs that implement these activities, visit the book’s website at www.java24hours.com.