ptg7068951
82 HOUR 7:Using Conditional Tests to Make Decisions
The statement that follows the ifconditional only is executed if the condi-
tional 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 2 and ends with the closing bracket }on Line 13. Create a
new empty Java file called Gamein NetBeans and enterthe text in Listing 7.1.
LISTING 7.1 TheGameProgram
1: classGame {
2: public static voidmain(String[] arguments) {
3: int total = 0;
4: int score = 7;
5: if (score == 7) {
6: System.out.println(“You score a touchdown!”);
7: }
8: if (score == 3) {
9: System.out.println(“You kick a field goal!”);
10: }
11: total = total + score;
12: System.out.println(“Total score: “+ total);
13: }
14: }
When you run the program, the output should resemble Figure 7.1.
FIGURE 7.1
The output of the Gameprogram.
You can use block statements in ifstatements to make the computer do
more than one thing if a condition is true. The following is an example of
an ifstatement 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;
}