-
Notifications
You must be signed in to change notification settings - Fork 0
Scanner – Taking User Input
Now that we know how to print messages, let’s learn how to ask the user for input!
➡️ Scanner is a special tool in Java that lets us take input from the keyboard.
Imagine your Java program is like a robot that can talk.
- Right now, it can print messages (
System.out.println(...)), but it can’t listen to you! - With Scanner, we can make the robot ask questions and process answers.
Before using Scanner, we need to import it. Think of this like grabbing a notepad so the robot can take notes.
import java.util.Scanner;- This tells Java that we want to use Scanner.
- Java already has Scanner built-in—we just need to bring it into our program.
To start using Scanner, we need to turn it on.
Scanner scanner = new Scanner(System.in);-
Scanner scanner→ Creates a Scanner object (our robot’s "ears"). -
new Scanner(System.in)→ Tells it to listen for keyboard input.
Let’s ask for the user’s name and print it back!
import java.util.Scanner; // Step 1: Import Scanner
public class UserInput {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in); // Step 2: Create Scanner
System.out.print("Enter your name: "); // Step 3: Ask for input
String name = scanner.nextLine(); // Step 4: Capture what they type
System.out.println("Hello, " + name + "!"); // Step 5: Use the input
}
}Enter your name: Alex
Hello, Alex!
➡️ .nextLine() captures everything the user types and stores it in name.
➡️ The program prints a message using their name.
Scanner can take different types of input, not just text!
| Data Type | Scanner Method | Example Input |
|---|---|---|
String (text) |
scanner.nextLine(); |
"Alex" |
int (whole number) |
scanner.nextInt(); |
25 |
double (decimal number) |
scanner.nextDouble(); |
3.14 |
import java.util.Scanner;
public class UserInfo {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in); // Create Scanner
System.out.print("Enter your name: ");
String name = scanner.nextLine(); // Take name input
System.out.print("Enter your age: ");
int age = scanner.nextInt(); // Take age input
System.out.println("Hello, " + name + "! You are " + age + " years old.");
scanner.close(); // Close Scanner
}
}Enter your name: Emily
Enter your age: 22
Hello, Emily! You are 22 years old.
➡️ .nextInt() takes a whole number.
➡️ .nextLine() takes text.
After using Scanner, we always close it to free up memory.
scanner.close();Think of this like turning off the robot’s ears when we’re done talking.
| Method | What It Captures | Example Input |
|---|---|---|
.nextLine() |
A full sentence (String) | "Hello world" |
.nextInt() |
A whole number (int) | 42 |
.nextDouble() |
A decimal number (double) | 3.14 |
.nextBoolean() |
A true/false value | true |