01 - Input
Reading User Input (Scanner)
What is it?
Input is data the user types into the program while it’s running. Java reads this using the Scanner class - a tool built into Java’s standard library.
Why does it exist?
Without input, programs are static - they do the same thing every time. Input makes programs dynamic and interactive (e.g., asking a user for their name, a number to calculate, etc.).
How does it work?
Step 1 - Import Scanner
Scanner isn’t available by default. You have to import it at the top of your file:
import java.util.Scanner;
This tells Java: “I want to use the Scanner class from the java.util package.”
Step 2 - Create a Scanner object
Scanner scanner = new Scanner(System.in);
Breaking this down:
| Part | Meaning |
|---|---|
Scanner |
The type (class) we’re using |
scanner |
The variable name we chose (can be anything) |
new Scanner(...) |
Creates a new Scanner instance |
System.in |
The input stream - i.e., what the user types in the keyboard |
Note
System.inis the keyboard input, just likeSystem.outis the screen output.
Step 3 - Read input with nextLine()
String userInput = scanner.nextLine();
scanner.nextLine()pauses the program, waits for the user to type something and press Enter, then returns what they typed as aString- You store it in a variable to use it later
Full working example
import java.util.Scanner;
public class InputExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("What is your name?");
String name = scanner.nextLine();
System.out.println("Hello, " + name + "!");
}
}
If user types Alice:
What is your name?
Alice
Hello, Alice!
Reading Different Types of Input
nextLine() always returns a String. To read numbers, you need to either use a different method or convert the string:
| Method | Returns | Use when |
|---|---|---|
scanner.nextLine() |
String |
Reading text or a whole line |
Integer.parseInt(scanner.nextLine()) |
int |
Reading a whole number |
Double.parseDouble(scanner.nextLine()) |
double |
Reading a decimal number |
System.out.println("Enter your age:");
int age = Integer.parseInt(scanner.nextLine());
System.out.println("You are " + age + " years old.");
Tip Prefer
scanner.nextLine()+Integer.parseInt()overscanner.nextInt(). ThenextInt()method leaves a leftover newline character in the buffer which causes bugs when you later try to read a string.
Gotchas
- Forgetting
import java.util.Scanner;→Scannerwon’t be found, compilation error scanner.nextLine()blocks (pauses) the program until Enter is pressed - this is intentional- If the user types letters when you expect a number and use
Integer.parseInt(), it will throw aNumberFormatExceptionat runtime