Completion requirements
Read this chapter, which reviews how computers make decisions using if statements. As you read this tutorial, you will understand that sometimes it is important to evaluate the value of an expression and perform a task if the value comes out to be true and another task if it is false. In particular, try the simulated program under the heading "Simulated Program" to see how a different response is presented to the user based on if a number is positive or negative.
Pay special attention to the "More Than One Statement per Branch" header to learn how the 'else' statement is used when there is more than one choice.
12. Box Office Program
Answer:
if ( age < 13 )
Box Office Program
Here is the program with the blank filled in correctly:
import java.util.Scanner; public class BoxOffice { public static void main (String[] args) { Scanner scan = new Scanner( System.in ); int age; System.out.println("Enter your age:"); age = scan.nextInt(); if ( age < 13 ) { System.out.println("Child rate."); } else { System.out.println("Adult rate."); } System.out.println("Enjoy the show."); } } |
Here is what happens for one run of the program:
- The program prints "Enter your age".
- The user enters an age: "21", for example.
- The string "21" is converted from characters into an
int
and put into the variableage.
- The condition
age < 13
is tested. 21 < 13
is false.- The false branch is executed: the program prints "adult rate".
- Execution continues with the statement after the false branch: "Enjoy the show" is printed.
Question 12:
What does the program output if the user enters 11?