Variable Initialization: Movie Review Recording Program
Problem Description
1. Problem Background and Purpose
This program simulates the basic functionality of a movie review app. Actual websites and apps also perform processing where user-input information is temporarily stored in memory before being displayed on screen. Through this problem, you'll learn how to use variables, one of the most fundamental concepts in programming.
Understanding variables is the first step in learning programming. Once you can use variables, you'll be able to learn more advanced control structures like conditional branching and loops.
2. Detailed Explanation of Prerequisites
What is a Variable?
A variable is a named box for temporarily storing data while a program is running. For example, imagine you place a box labeled "Movie Title" on your desk and put a note saying "The Matrix" inside it. Program variables work exactly the same way.
Variables have types called "data types." This is like a rule that determines what can be put in the box:
- String type: A box for storing strings (collections of characters). Used for text information like movie titles and reviews.
- int type: A box for storing integers (-2, -1, 0, 1, 2...). Used for numeric information like rating scores.
- double type: A box for storing numbers with decimals. Not used here, but useful for handling average scores (like 8.5 points).
What is the Scanner Class?
Scanner is a tool provided standard in Java for reading input from the keyboard. Without it, programs cannot receive values entered by users.
Using Scanner requires two steps:
- Import: Write
import java.util.Scanner;to make the Scanner class available - Create Object: Write
Scanner sc = new Scanner(System.in);to prepare for actually reading input
Here, System.in means "standard input," which usually refers to the keyboard. In other words, it means "create a Scanner to read input from the keyboard."
Why Variables are Necessary
Without variables, you could only use input values immediately and discard them. For example, you'd have to input a movie title and display it immediately, then input a rating and display it immediately... You could only handle one piece of information at a time.
With variables, you can make the program "remember" multiple pieces of information in memory and use them later at any timing in any order. This becomes the foundation for programs to perform complex processing.
3. Detailed Line-by-Line Code Explanation
Step 1: Scanner Preparation
Scanner sc = new Scanner(System.in);
```java
This line creates a Scanner object. The newly created Scanner is assigned to a variable named `sc`. At this point, the program is ready to receive input from the keyboard.
We named the variable `sc` as an abbreviation of "Scanner." Of course, names like `scanner` or `input` would work too, but short, understandable names are common.
### Step 2: Reading Movie Title
```java
String title = sc.nextLine();
```java
When this line executes, the program pauses and waits until the user presses Enter. When the user types "The Matrix" and presses Enter:
1. `sc.nextLine()` reads the string "The Matrix"
2. That string is assigned to a variable named `title`
3. At this point, a box named "title" is created in memory with the value "The Matrix" inside
`nextLine()` is a method meaning "read the next line." It reads all characters until Enter is pressed.
### Step 3: Reading Rating
```java
int rating = sc.nextInt();
```java
This line reads an integer. When the user types "9" and presses Enter:
1. `sc.nextInt()` converts the character "9" into the integer 9
2. That integer is assigned to an int variable named `rating`
3. A box named "rating" is created in memory with the numeric value 9 inside
**Important Note**: `nextInt()` only reads the number and doesn't read the newline character from Enter. This newline character remains in memory, causing problems in the next processing.
### Step 4: Consuming Newline Character
```java
sc.nextLine();
```java
This line may seem to do nothing, but it's actually very important. It "consumes" the newline character left by `nextInt()`.
Without this line, the next `nextLine()` would read the newline character, and the program would proceed before the user can input a review. As a result, `reviewComment` would contain an empty string (a string with nothing in it).
This is a point where beginners very often make mistakes. **When using `nextLine()` after `nextInt()` or `nextDouble()`, always insert an empty `nextLine()` in between.**
### Step 5: Reading Review
```java
String reviewComment = sc.nextLine();
```java
This line reads the review comment. Since we consumed the newline character earlier, the user's actual input (e.g., "Amazing visual effects!") is correctly read here.
### Step 6: Data Output
```java
System.out.println("Movie: " + title);
System.out.println("Rating: " + rating);
System.out.println("Review: " + reviewComment);
```java
Here, we output the values of the three stored variables. Using the `+` operator allows concatenating (joining) strings and variable values.
For example, the first line `"Movie: " + title`:
- The string "Movie: "
- The value of the `title` variable ("The Matrix")
Are concatenated to create one string "Movie: The Matrix". Then `println()` outputs it to the screen.
**Important Point**: Values stored in variables can be used multiple times. If you write `System.out.println(title);` on line 4, you could display the title again. This is the greatest advantage of variables.
### Step 7: Resource Release
```java
sc.close();
```java
Finally, we close the Scanner to release resources. This is like "putting away tools you're done using" - returning memory and system resources the program was using.
## 4. Common Mistakes and Fixes
### Mistake 1: Forgetting nextLine() after nextInt()
**Wrong Example**:
```java
int rating = sc.nextInt();
String reviewComment = sc.nextLine(); // Becomes empty string
```java
**Reason**: `nextInt()` leaves a newline character, so the next `nextLine()` reads that.
**Correct Example**:
```java
int rating = sc.nextInt();
sc.nextLine(); // Consume newline character
String reviewComment = sc.nextLine(); // Correctly read review
```java
### Mistake 2: Wrong Data Type
**Wrong Example**:
```java
String rating = sc.nextLine(); // Reading rating as string
```java
**Reason**: Rating is numeric, so it should be read as int type. Making it a string prevents calculations later (like finding average).
**Correct Example**:
```java
int rating = sc.nextInt(); // Read as number
```java
### Mistake 3: Duplicate Variable Names
**Wrong Example**:
```java
String title = sc.nextLine();
String title = "Default Title"; // Compile error
```java
**Reason**: You cannot declare a variable with the same name twice.
**Correct Example**:
```java
String title = sc.nextLine();
title = "Default Title"; // Assign new value to existing variable (not redeclaration)
```java
### Mistake 4: Forgetting Scanner Import
**Wrong Example**:
```java
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in); // Compile error
}
}
```java
**Reason**: Scanner class is in the java.util package, so import is required before use.
**Correct Example**:
```java
import java.util.Scanner; // Import at top of file
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in); // OK
}
}
```java
## 5. Practical Debugging Tips
### How to Check Variable Values
When a program doesn't work as expected, check if variables contain the correct values.
```java
String title = sc.nextLine();
System.out.println("Debug: title = " + title); // Debug output
```java
By outputting variable values midway like this, you can identify where problems occur.
### Checking if Input is Read Correctly
If output is empty, input reading method may be wrong. Check these patterns:
- Using `nextLine()` after `nextInt()` → Insert empty `nextLine()` in between
- Not enough input lines → Check test case input
- Data type mismatch → Correctly use String/int/double
### Common Error Messages
1. **NoSuchElementException**: Tried to read when no input exists
- Solution: Check if input data is correctly provided
2. **InputMismatchException**: Input differs from expected type
- Solution: Check if string input where number expected
3. **Cannot find symbol: Scanner**: Scanner not imported
- Solution: Add `import java.util.Scanner;` at top of file
## 6. Advanced Topics
### More Practical Movie Review System
Improving this program allows adding features like:
- Check if rating is within 1-10 range (after learning conditional branching)
- Store multiple movie reviews (after learning arrays)
- Calculate average rating of reviews (after learning loops and calculations)
- Save reviews to file (after learning file I/O)
### Variable Scope (Effective Range)
Variables have a concept called "scope." This indicates where the variable can be used, and is basically only valid inside the curly braces `{}` where it was declared.
```java
public static void main(String[] args) {
String title = "Movie"; // This variable is only valid inside main method
{
String review = "Good"; // This variable is only valid inside this block
}
// System.out.println(review); // Error: review is out of scope
}
```java
### Memory Management Basics
When you declare a variable, space is allocated in computer memory (RAM). Int type is usually 4 bytes, String varies by content, but the reference (address) itself is fixed size.
When the program ends, Java's garbage collector automatically releases unused memory, so unlike C language, manual memory management is not required.
## 7. Related Learning Topics
Topics to learn next:
- **Conditional Branching (if statement)** (Category 004): Check if rating is within range
- **Loops (for/while)** (Category 005): Process multiple reviews
- **Arrays** (Category 006): Store multiple movie data
- **Methods** (Category 008): Functionalize review display processing
- **Class Design** (Category 007): Create Movie class to organize information
Concepts related to this problem:
- **Data Type Details** (Category 001-002): Types and usage of basic data types
- **Operators** (Category 003): String concatenation and arithmetic operations
- **Exception Handling** (Category 019): Handling invalid input.
Test Cases
※ Output examples follow programming industry standards
The Matrix 9 Amazing visual effects!
Movie: The Matrix Rating: 9 Review: Amazing visual effects!
Inception 10 Mind-bending masterpiece
Movie: Inception Rating: 10 Review: Mind-bending masterpiece
Short Film 1 Okay
Movie: Short Film Rating: 1 Review: Okay
The Godfather 8 Classic crime drama with excellent acting
Movie: The Godfather Rating: 8 Review: Classic crime drama with excellent acting
A 5 B
Movie: A Rating: 5 Review: B
Your Solution
You have 6 free executions remaining
