Syntax
Scanner scanner = new Scanner(System.in);Examples
Reading Basic Input
Reading a line of text and a number from the console.
import java.util.Scanner;
public class InputExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = scanner.nextLine();
System.out.print("Enter your age: ");
int age = scanner.nextInt();
System.out.println("Hello " + name + ", you are " + age + " years old");
scanner.close();
}
}Reading Multiple Value Types
Using the type-specific methods Scanner provides for cleaner parsing.
import java.util.Scanner;
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a price: ");
double price = scanner.nextDouble();
System.out.print("Are you a member? (true/false): ");
boolean isMember = scanner.nextBoolean();
double finalPrice = isMember ? price * 0.9 : price;
System.out.println("Final price: " + finalPrice);Input Validation Loop
Repeating a prompt until valid input is provided, using hasNextInt() to check before reading.
import java.util.Scanner;
Scanner scanner = new Scanner(System.in);
int number = 0;
boolean valid = false;
while (!valid) {
System.out.print("Enter a whole number: ");
if (scanner.hasNextInt()) {
number = scanner.nextInt();
valid = true;
} else {
System.out.println("That's not a valid number, try again");
scanner.next(); // discard the invalid token
}
}
System.out.println("You entered: " + number);Best practices
- Always close the Scanner when done (scanner.close()) to release the underlying resource, especially in larger applications
- Be careful mixing nextInt()/nextDouble() with nextLine() - the numeric methods don't consume the trailing newline, which can cause an empty read on the next nextLine() call
- Use hasNextInt(), hasNextDouble(), etc. to validate input before attempting to read it, avoiding an InputMismatchException
- Create one Scanner instance for System.in per program rather than opening multiple - reusing the same instance avoids resource conflicts
Runtime & versions
Java Virtual Machine. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
Java Language Specification