3. Interacting with Users: The Scanner Class
A program that only talks to itself isn't very useful. To build tools, games, or systems, you need to listen to the user. In Java, the most common way to do this is by using the Scanner class.
1. The Setup: Importing the Tool
Java is modular. To keep programs small, Java doesn't load every tool automatically. The Scanner lives in the java.util package, so we must "invite" it into our code at the very top of the file.
import java.util.Scanner;
2. Creating the Scanner Object
Think of the Scanner as an "ear" for your program. You need to create this ear and point it toward the keyboard (System.in).
Scanner input = new Scanner(System.in);
3. How to Capture Different Data Types
Depending on what the user types (a name, an age, or a price), you need to use a specific "method."
| Method | Used For | Example Result |
|---|---|---|
nextLine() |
Full sentences/Text | "Your Name" |
nextInt() |
Whole Numbers | 25 |
nextDouble() |
Decimal Numbers | 19.99 |
next() |
A single word | "Hello" |
💻 Full Practical Example
Copy this into a file named UserInteraction.java:
import java.util.Scanner;
public class UserInteraction {
public static void main(String[] args) {
// 1. Initialize the Scanner
Scanner reader = new Scanner(System.in);
// 2. Ask for a String
System.out.print("Enter your username: ");
String username = reader.nextLine();
// 3. Ask for an Integer
System.out.print("Enter your age: ");
int age = reader.nextInt();
// 4. Output the results
System.out.println("\n--- Profile Summary ---");
System.out.println("User: " + username);
System.out.println("In 10 years, you will be: " + (age + 10));
// 5. Always close the scanner to free up system resources
reader.close();
}
}
⚠️ The "Skip" Bug (Essential Tip)
There is a common issue when using nextInt() followed by nextLine().
When a user types a number and hits Enter, nextInt() grabs the number, but the "Enter" (the newline character) stays in the memory. The next nextLine() will "grab" that Enter key and immediately skip the input, leaving your variable empty.
The Solution: Add an extra reader.nextLine(); right after your nextInt(); to "clean" the scanner's memory.
This is wrong , try it to see :
int age = reader.nextInt();
String city = reader.nextLine();
You need to do like this :
int age = reader.nextInt();
reader.nextLine(); // This "eats" the Enter key so the next input works!
String city = reader.nextLine();
💡 Challenge: The Personal Invoice
Try to write a program that asks a user for:
- The name of an item.
- The price of the item.
- The quantity they want to buy.
Then, calculate and display the Total Cost. (Hint: total = price * quantity) ```