Variable Assignment: Recipe Card
Problem Description
In this problem, you will create a program that reads recipe information (dish name, servings, cooking time, and main ingredient) using Scanner, assigns each value to the appropriate variable type, and displays the result in a Recipe Card format to standard output.
[Explanation]
1. Problem Overview
This problem teaches one of the most fundamental concepts in Java programming: variable assignment. A variable is a named box that temporarily stores data during program execution. In actual development, it is common to receive user input, store it in variables of appropriate types, and process it. Through this problem, you will learn how to receive input using Scanner and how to assign values to variables of different data types.
2. Prerequisites
What is a variable?
A variable is a named box that temporarily stores data during program execution. For example, if you want to use a recipe name entered by the user later, you store that recipe name in a variable.
Data Types
In Java, you must specify the type of data for variables:
- String: Type for storing text (e.g., "Pasta Carbonara")
- int: Type for storing integers (e.g., 2, 20)
- double: Type for storing decimals (e.g., 3.14)
Scanner class
Scanner is a convenient class for reading input from the keyboard. Create it with new Scanner(System.in), and use nextLine() to read strings and nextInt() to read integers.
Assignment operator (=)
Storing data in a variable is called assignment and uses the = symbol. Example: String name = "Alice"; assigns the string "Alice" to the variable name.
3. Code Explanation (Step by Step)
Step 1: Create Scanner Object
Scanner sc = new Scanner(System.in);
This line creates a Scanner object for reading keyboard input. System.in represents keyboard input, and by passing it to Scanner, you prepare to read input from the keyboard. By storing the Scanner object in the variable sc, you can use it like sc.nextLine() afterwards.
Step 2: Read and Store Recipe Name
String dish = sc.nextLine();
Read one line of text entered by the user from the keyboard and assign it to the String variable dish. For example, if the user enters "Pasta Carbonara", at this point the variable dish stores the string "Pasta Carbonara".
Step 3: Read and Validate Servings
int servings = sc.nextInt();
if (servings <= 0) {
System.out.println("Error: Servings must be positive");
return;
}
Read the integer entered by the user and assign it to the int variable servings. Then check if the input value is positive. If a value of 0 or less is entered, display an error message and exit the program. This validation prevents the program from malfunctioning with invalid data.
Step 4: Read Cooking Time
int time = sc.nextInt();
sc.nextLine(); // Consume newline character
Read the cooking time as an integer and store it in the variable time. Important is the next line sc.nextLine(). nextInt() only reads the number and does not read the subsequent newline character (Enter key). Therefore, if you use nextLine() next, it will only read the remaining newline character, and you won't be able to read the intended string. To prevent this, you need to consume the newline character.
Step 5: Read Main Ingredient
String ingredient = sc.nextLine();
Read the main ingredient as a string and store it in the variable ingredient. Since the newline character was consumed in Step 4, this nextLine() correctly reads the user's input.
Step 6: Display Stored Data
System.out.println("=== Recipe Card ===");
System.out.println("Dish: " + dish);
System.out.println("Servings: " + servings + " people");
System.out.println("Time: " + time + " minutes");
System.out.println("Ingredient: " + ingredient);
Use the data stored in variables to display output in the specified format. The + operator is used to concatenate strings. For example, "Dish: " + dish joins the string "Dish: " with the value of the variable dish. Although servings and time are integers, they are automatically converted to strings when concatenated with +.
Step 7: Error Handling
try {
// Main processing
} catch (Exception e) {
System.out.println("Error: Invalid number format");
} finally {
sc.close();
}
The try-catch block catches errors in numeric input. If the user enters text where a number is expected, an InputMismatchException is thrown, but the catch block catches it and displays a helpful error message. The finally block ensures that the Scanner is always closed whether or not an error occurred, properly releasing resources.
4. Common Mistakes and Corrections
Mistake 1: Handling newline characters when using nextLine() after nextInt()
Incorrect example:
int servings = sc.nextInt();
int time = sc.nextInt();
String ingredient = sc.nextLine(); // Only the newline character is read
Ready to Try Running Code?
Log in to access the code editor and execute your solutions for this problem.
Don't have an account?
Sign Up