005-001-006
Movie Ticket Price Calculator: Conditional Branching by Age
Medium
Problem Description
[Explanation]
1. Problem Overview
Using a movie theater pricing system as a theme, we learn conditional branching with if statements. Since actual movie theaters also vary prices by age, recreating a familiar system with a program helps understand the practical utility of conditional branching. This learning leads to the next steps: complex conditional judgments and switch statements.
2. Prerequisites
What is Conditional Branching
Conditional branching is a mechanism where a program makes an "if-then" judgment and executes different processes depending on conditions. It's the same as everyday decisions like "if it's raining, take an umbrella; otherwise, don't."
Basic if Statement Syntax
if (condition) {
// Process executed when condition is true
} else if (another_condition) {
// Process executed when first condition is false and this condition is true
} else {
// Process executed when all conditions are false
}
```java
### Comparison Operators
- `<` : less than
- `<=` : less than or equal to
- `>` : greater than
- `>=` : greater than or equal to
- `==` : equal to
- `!=` : not equal to
### Logical Operators
- `||` (OR): whole is true if any one is true
- `&&` (AND): whole is true only if all are true
## 3. Code Explanation (Step by Step)
### Step 1: Scanner Preparation and Input Reading
```java
Scanner sc = new Scanner(System.in);
int age = sc.nextInt();
```java
First, create a Scanner object to prepare for receiving user input. `new Scanner(System.in)` means "prepare a tool to read data from standard input (keyboard)". Next, read an integer value with the `nextInt()` method and store it in variable age. At this point, the variable age contains the input age as an integer.
### Step 2: Error Case Check (Early Return Pattern)
```java
if (age < 0 || age > 150) {
System.out.println("Error: Invalid age");
}
```java
First, check for invalid values. If age is below 0 or above 150, these are unrealistic values, so display an error message. Using `||` (logical OR) creates a condition where "the whole is true if either one is true". Processing error cases early like this is called the "early return pattern" and is an important technique for improving code readability.
### Step 3: Child Price Judgment
```java
else if (age <= 12) {
System.out.println("Child: 1000 yen");
}
```java
If the first if statement is false (meaning within valid age range), check the next condition. If age is 12 or below, display child price (1000 yen). Using `<=` (less than or equal to) includes exactly 12 in child price. Be careful - if you use `<` (less than), 12 would not be included.
### Step 4: Senior Price Judgment
```java
else if (age >= 65) {
System.out.println("Senior: 1200 yen");
}
```java
If age is 65 or above, display senior price (1200 yen). Here, using `>=` (greater than or equal to) applies senior price from exactly 65.
### Step 5: Adult Price Judgment (else handles all remaining)
```java
else {
System.out.println("Adult: 1800 yen");
}
```java
If none of the previous conditions matched (meaning age 13-64), display adult price (1800 yen). The important point here is that using else allows processing "all remaining" cases at once. While you could explicitly write `age >= 13 && age <= 64`, using else is simpler and more readable since other conditions already narrowed down the cases.
### Step 6: Resource Cleanup
```java
sc.close();
```java
Finally, close the Scanner object to release system resources. This is good programming practice - always closing resources when finished prevents problems like memory leaks.
## 4. Common Mistakes
### Mistake 1: Boundary Value Judgment Error
```java
// ❌ Wrong: 12 years old becomes adult price
if (age < 12) {
System.out.println("Child: 1000 yen");
}
// ✅ Correct: Include 12 in child price
if (age <= 12) {
System.out.println("Child: 1000 yen");
}
```java
**Reason**: Using `<` (less than) doesn't include 12. Check the problem specification carefully for boundary values and choose correctly between `<=` (less than or equal) and `<` (less than).
### Mistake 2: Inappropriate Condition Order
```java
// ❌ Wrong: Other conditions won't be evaluated if else comes first
if (age >= 13 && age <= 64) {
System.out.println("Adult: 1800 yen");
} else if (age <= 12) {
System.out.println("Child: 1000 yen");
}
```java
**Reason**: If the first condition is too broad or overlaps, subsequent conditions won't be evaluated. The recommended order is: error cases first, then special cases, finally general cases.
### Mistake 3: Logical Operator Misuse
```java
// ❌ Wrong: AND makes both conditions never true together
if (age < 0 && age > 150) {
System.out.println("Error: Invalid age");
}
// ✅ Correct: OR makes error if either one is true
if (age < 0 || age > 150) {
System.out.println("Error: Invalid age");
}
```java
**Reason**: Using `&&` (AND) creates a contradictory condition "below 0 AND above 150" that's always false. Error checks typically use `||` (OR).
## 5. Practical Debugging Hints
### Debug Method 1: Check Variable Values
```java
int age = sc.nextInt();
System.out.println("Debug: age = " + age); // Debug output
```java
Temporarily output variable values to confirm input is read correctly.
### Debug Method 2: Check Condition Results
```java
boolean isChild = (age <= 12);
System.out.println("Debug: isChild = " + isChild);
```java
Store condition results in boolean variables to verify they return expected results.
### Common Error Messages
- **InputMismatchException**: Occurs when non-integer values (like strings) are input. NextInt() only accepts integers.
- **Compilation error "else without if"**: Check if there are other statements between if and else statements.
## 6. Advanced Topics
### Advanced 1: More Detailed Pricing System
Actual movie theaters have even finer pricing:
- Student discount
- Disability discount
- Late show pricing
Implementing these requires combining conditions other than age (e.g., student ID possession).
### Advanced 2: Migration to switch Statement
When branching by specific values, switch statements can be more readable. However, if statements are better suited for range judgments (like age 12 or below).
### Advanced 3: Using Constants
Defining prices as constants makes changes easier:
```java
final int CHILD_PRICE = 1000;
final int ADULT_PRICE = 1800;
final int SENIOR_PRICE = 1200;
```java
## 7. Related Learning Topics
Topics to learn next:
- **switch statement** (Category 005-002): Multi-way branching by specific values
- **Logical operator details** (Category 005-003): Building complex conditional expressions
- **Ternary operator** (Category 005-004): Concise conditional expression writing
- **Nested if statements** (Category 005-005): Placing conditions within conditions.
Test Cases
※ Output examples follow programming industry standards
Input:
8
Expected Output:
Child: 1000 yen
Input:
25
Expected Output:
Adult: 1800 yen
Input:
70
Expected Output:
Senior: 1200 yen
Input:
12
Expected Output:
Child: 1000 yen
Input:
13
Expected Output:
Adult: 1800 yen
Input:
64
Expected Output:
Adult: 1800 yen
Input:
65
Expected Output:
Senior: 1200 yen
Input:
-5
Expected Output:
Error: Invalid age
Input:
200
Expected Output:
Error: Invalid age
❌ Some tests failed
Your Solution
Current Mode:● My Code
99
1
2
3
4
5
6
7
8
9
10
›
⌄
⌄
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Write your code here
sc.close();
}
}
0 B / 5 MB
You have 5 free executions remaining
