Sams Teach Yourself Java™ in 24 Hours (Covering Java 7 and Android)

(singke) #1
ptg7068951

if-else Statements 83

The brackets are used to group all statements that are part of the ifstate-
ment. If the variable playerScoreis greater than 9,999, three things happen:


. The value of the playerLivesvariable increases by one (because the
increment operator ++is used).
. The text “Extra life!” is displayed.
. The value of the difficultyLevelvariable is increased by 5.


If the variable playerScoreis not greater than 9,999, nothing happens. All
three statements inside the ifstatement 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 ifstatement, 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 elsestatement does not have a condition listed alongside it, unlike the
ifstatement. The elsestatement is matched with the ifstatement that
immediately precedes it. You also can use elseto chain several ifstate-
ments 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. What went wrong?”);
} else{
System.out.println(“You got an F. You’ll do well in Congress!”);
}


By putting together several different ifand elsestatements in this way,
you can handle a variety of conditions. The preceding example sends a spe-
cific message to Astudents, B students, C students, and future legislators.

Free download pdf