User Input and Display โจ๏ธ¶
Mentor's Note: In Java, input is a bit more formal than in other languages. You need to "import" a special worker called the
Scanner. ๐ก
๐ The Scenario: The Customer Receipt ๐งพ¶
Imagine you are at a checkout counter.
- The Logic: The clerk scans your item (Input). ๐ฆ
- The Result: The total is printed on your receipt (Output). โ
๐ป Implementation: The Scanner Lab¶
// ๐ Scenario: Greeting a Customer
// ๐ Action: Using the Scanner class to read data
import java.util.Scanner; // ๐ฆ 1. Import the worker
public class GreetingLab {
public static void main(String[] args) {
// ๐ฆ 2. Create the Scanner object
Scanner scanner = new Scanner(System.in);
// --- Taking String Input (Text) ๐ ---
System.out.print("Enter your name: ");
String name = scanner.nextLine(); // Reads the whole line
System.out.println("Hello, " + name + "!");
// --- Taking Integer Input (Numbers) ๐ข ---
System.out.print("Enter your age: ");
int age = scanner.nextInt(); // Reads only the next integer
System.out.println("You are " + age + " years old.");
// ๐ฆ 3. Close the worker (Best Practice)
scanner.close();
}
}
๐ Key Concepts¶
Scanner: A powerful Java class used to read user input. You mustimportit first.System.in: This tells the Scanner to "listen" to your keyboard.nextLine(): Used for reading sentences (text).nextInt(): Used for reading whole numbers.close(): Always close your Scanner when finished to save computer resources.
๐ง Step-by-Step Logic¶
- Start ๐
- Bring in the
Scannertool (import). - Set up the
Scannerto listen to the keyboard (new Scanner(System.in)). - Prompt the user: "Enter your name: ".
- Store the user's typed text into a
Stringvariable. - Display the message back.
- End ๐
๐ฏ Practice Lab ๐งช¶
Task: Calculator
Task: Ask the user for two numbers, add them together, and print the total.
Hint: Use scanner.nextInt() twice and a sum variable. ๐ก
Quick Quiz¶
Quick Quiz
Which package must you import to use the Scanner class? - [ ] java.io - [ ] java.lang - [x] java.util - [ ] java.swing
Explanation: The Scanner class is located in the java.util (Utility) package.