Conditional Statements InJava


Writing a computer program has been compared to telling a household robot what to do. You provide the computer 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 will work them out for you. Tell it to display some information, and it will dutifully respond.

However, 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 warning could be something along the lines of Hear that bouncing noise? It's your checks. The computer should display this message only if your account is overdrawn. If it isn't, the message would be both inaccurate and emotionally upsetting.

The way to accomplish this task in a Java program is to use a statement called a conditional. Conditionals cause something to happen in a program only if a specific condition is met. Country star Kenny Rogers sang with the hippie-rock group The First Edition in the late '60s, and one of the group's singles hit the top 5 in 1968: "Just Dropped In (To See What Condition My Condition Was In)". During this hour, you'll be dropping in to check the condition of several things in your Java programs using the conditional statements if, else, switch, case, and break. You also will be using several conditional operators: ==, !=, <, >, and ?. The following topics will be covered:

·         Testing to see whether conditions are met

·         Using the if statement for basic conditional tests

·         Using other statements in conjunction with if

·         Testing whether one value is greater than or less than another

·         Testing whether two values are equal or unequal

·         Using else statements as the opposite of if statements

·         Chaining several conditional tests together

·         Using the switch statement for complicated conditional tests

·         Creating complicated tests with the ternary operator

if Statements

If you want to test a condition in a Java program, the most basic way is with an if statement. As you learned previously, the boolean variable type is used to store only two possible values: true or false. The if statement works along the same lines, testing to see whether a condition is true or false and taking action only if the condition is true.

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

if (account < 0.01)

    System.out.println("Hear that bouncing noise? It's your checks");

Although this code is listed on two lines, it's one statement. The first part uses if to determine whether the account variable is less than 0.01 by using the < operator. The second part displays the text Hear that bouncing noise? It's your checks. The second part of the if statement will be run only if the first part is true. If the account variable has a value of 0.01 (1 cent) or higher, the println statement will be ignored. Note that the condition that you test with an if statement must be surrounded by parentheses, as in (account < 0.01).

If you're not sure why if (account < 0.01) is not a statement on its own, note that there is no semicolon at the end of the line. In Java programs, semicolons are used to show where one statement ends and the next one begins. In the preceding example, the semicolon does not appear until after the println portion of the statement. If you put a semicolon after the if portion, as in if (account < 0.01);, you'll cause an error in your program that can be hard to spot. Take care regarding semicolons when you start using the if statement.

The less than operator, <, is one of several different operators that you can use with conditional statements. You'll become more familiar with the if statement as you use it with some of the other operators.

Less Than and Greater Than Comparisons

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

if (elephantWeight > 780)

    System.out.println("This elephant is too fat for your 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.

One thing to learn about if statements is that they often cause nothing to happen in your programs. If the preceding two statements are used in a program where elephantWeight is equal to 600 and elephantTotal is equal to 10, the rest of the statements will be ignored. It's as though you are giving an order to a younger sibling who is subject to your whims: "Jerry, go to the store. If they have Everlasting Gobstopper candy, buy some for me. If not, do nothing and await further orders."

There will be times when you will want to determine whether something is less than or equal to something else. You can do this with the <= operator, as you might expect; use the >= operator for greater-than-or-equal-to tests. Here's an example:

if (account <= 0)

    System.out.println("Hear that bouncing noise? It's your checks");

This revision of the checkbook example mentioned previously should be a bit easier to understand. It tests whether account is less than or equal to the value 0 and taunts the user if it is.

Equal and Not Equal Comparisons

Another condition to check on 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 == value, as in the following statements:

if (answer == rightAnswer)

    studentGrade = studentGrade + 10;

if (studentGrade == 100)

    System.out.println("Congratulations -- a perfect score!");

 

Caution: The operator used to conduct equality tests has two equal signs: ==. It's very 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 also can test inequality--whether something is not equal to something else. You do this with the != operator, as shown in the following example:

if (team != "New York Jets")

    chanceToWin = 50;

if (answer != rightAnswer)

    score = score - 5;

You can use the == and != operators with every type of variable except for one, strings. To see whether one string has the value of another, use the equals() method described during Hour 6, "Using Strings to Communicate."

Organizing a Program with Block Statements

Up to this point, all of the if statements have been followed with a single instruction, such as the println() method. In many cases, you will want to do more than one action in response to an if statement. To do this, you'll use the squiggly bracket marks { and } to create a block statement.

Block statements are statements that are organized as a group. 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. 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 2 and ends with the closing bracket } on Line 11. Load your word processor and enter the text of Listing 7.1 as a new file.

Listing 7.1. A Java program using a main() block statement.

 

 1: class Game {

 2:     public static void main(String[] arguments) {

 3:         int total = 0;

 4:         int score = 7;

 5:         if (score == 7)

 6:             System.out.println("You score a touchdown!");

 7:         if (score == 3)

 8:             System.out.println("You kick a field goal!");

 9:         total = total + score;

10:         System.out.println("Total score: " + total);

11:     }

12: }


Save this file as Game.java and compile it with the javac compiler tool. The output should resemble Listing 7.2.

Listing 7.2. The output of the Game program.

You score a touchdown!

Total score: 7 You can also use block statements in conjunction with if statements to make the computer do more than one thing if a conditional statement is true. The following is an example of an if statement that includes a block statement:

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 will happen:

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

·         The text Extra life! is displayed.

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

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

if-else Statements

There are times when you want to do something if a condition is true and do 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:

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. Generally, the else statement is matched with the if statement that immediately comes before it in a Java program. 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. Great job!");

else if (grade == "B")

    System.out.println("You got a B. Good work!");

else if (grade == "C")

    System.out.println("You got a C. You'll never get into a good college!");

else

    System.out.println("You got an F. You'll do well in Congress!");

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

switch Statements

The if and else statements are good for situations with only two possible conditions, but there are times when you have more than two options that need to be considered. 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 to use the switch statement. You can use it in a Java program to test for a variety of different conditions and respond accordingly. In the following example, the grade example has been rewritten with the switch statement to handle a complicated range of choices:

 

switch (grade) {

    case `A':

        System.out.println("You got an A. Great job!");

        break;

    case `B':

        System.out.println("You got a B. Good work!");

        break;

    case `C':

        System.out.println("You got a C. You'll never get into a good college!");

        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 will be tested--in this example, grade. Then the switch statement uses the { and } brackets to form a block statement.

Each of the case statements checks the test variable from switch against a specific value. In this example, there are case statements for values of A, B, and C. Each of these has one or two statements that follow it. When one of these case statements matches the variable listed with 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! will be displayed. The next statement is break, so no other part of the switch statement will be considered. The break statement tells the computer to break out of the switch statement.

The default statement is used as a catch-all if none of the preceding case statements is true. In this example, it will occur 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 that you use in your programs. If it is omitted, nothing will happen if none of the case statements has the correct value.

The Conditional Operator

The most complicated conditional statement is one that you might not find reasons to use in your programs, the ternary operator. If you find it too confusing to implement in your own programs, take heart: You can use other conditionals to accomplish the same thing.

You can use the ternary operator when you want to assign a value or display a value based on a conditional test. For example, in a video game, you might need to set the numberOfEnemies variable based on whether the skillLevel variable is greater than 5. One way to do this is with an if-else statement:

if (skillLevel > 5)

    numberOfEnemies = 10;

else

    numberOfEnemies = 5;

A shorter way to do this is to use the ternary operator, which is ?. A ternary operator has the following parts:

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

·         A question mark (?)

·         The value to use if the condition is true

·         A colon (:)

·         The value to use if the condition is false

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

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

You can also 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. You could do this action with another if-else statement:

if (gender == "male")

    System.out.print("Mr.");

else

    System.out.print("Ms.");

A shorter method is to use the ternary operator to accomplish the same thing, as in the following:

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

The ternary operator can be useful, but it's also the hardest element of conditional tests in Java to understand. Feel free to use the longer if and else statements if you want.

Workshop: Watching the Clock

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

Run the word processor that you're using to create Java programs and give a new document the name ClockTalk.java. This program is long, but most of it consists of long conditional statements. Type the full text of Listing 7.3 into the word processor and save the file when you're done.

Post a Comment

أحدث أقدم