Java course menu
Java User Input with Scanner: nextInt, nextLine and Validation
Read keyboard input in Java with the Scanner class: reading numbers, words and whole lines, the nextInt + nextLine trap and how to fix it, checking input with hasNextInt, reading until the input ends, and closing the Scanner.
On this page
Programs become interactive when they read input. In Java, the easiest way to read what the user types is the Scanner class from java.util.
In the examples below, the output shows exactly what you would see in the terminal, including what the user typed after each prompt.
Creating a Scanner#
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Your name: ");
String name = in.next();
System.out.print("Your age: ");
int age = in.nextInt();
System.out.println("Hi " + name + ", next year you will be " + (age + 1));
}
}Your name: Asha
Your age: 21
Hi Asha, next year you will be 22new Scanner(System.in)reads from the keyboard (standard input).System.out.print(notprintln) keeps the cursor on the prompt line.- Create one Scanner for
System.inand reuse it for every read.
Scanner methods#
Reading whole lines#
next() stops at the first space. Use nextLine() for text that can contain spaces:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Full name: ");
String fullName = in.nextLine();
System.out.println("Hello, " + fullName + "!");
}
}Full name: Asha Rao
Hello, Asha Rao!The nextInt + nextLine trap#
After nextInt(), the Enter key the user pressed is still waiting in the input. A following nextLine() reads that empty remainder and returns "" immediately. Fix it by calling nextLine() once to consume the leftover line break:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Age: ");
int age = in.nextInt();
in.nextLine(); // discard the rest of the line
System.out.print("Full name: ");
String name = in.nextLine();
System.out.println(name + " is " + age + ".");
}
}Age: 21
Full name: Asha Rao
Asha Rao is 21.A popular alternative is to read every input with nextLine() and convert it yourself with Integer.parseInt(line.trim()).
Validating input#
If the user types abc where nextInt() expects a number, it throws an InputMismatchException. Check first with hasNextInt(), and skip bad input with next():
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int age;
while (true) {
System.out.print("Age: ");
if (in.hasNextInt()) {
age = in.nextInt();
if (age > 0 && age < 130) {
break;
}
} else {
in.next(); // throw away the invalid word
}
System.out.println("Please enter a whole number between 1 and 129.");
}
System.out.println("Thank you. You are " + age + ".");
}
}Age: abc
Please enter a whole number between 1 and 129.
Age: -5
Please enter a whole number between 1 and 129.
Age: 30
Thank you. You are 30.Reading until the input ends#
hasNextInt() returns false at the end of the input, which makes it easy to process a list of numbers:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int sum = 0;
int count = 0;
while (in.hasNextInt()) {
sum += in.nextInt();
count++;
}
System.out.println(count + " numbers, sum " + sum);
}
}4 8 15 16 23 42
6 numbers, sum 108In a terminal, end the input with Ctrl + D (macOS/Linux) or Ctrl + Z then Enter (Windows).
Closing the Scanner#
A Scanner wrapping a file should be closed when you are done (see File Handling). A Scanner on System.in is different: closing it also closes System.in, and no later code can read the keyboard again. In small programs, simply leave it open.
Common mistakes#
Practice#
Practice exercise
Ask for the width and height of a rectangle (decimals allowed) and print its area and perimeter. In the example run, the user types 4.5 and 2.
Show solution
import java.util.Scanner;
public class RectangleInput {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Width: ");
double width = in.nextDouble();
System.out.print("Height: ");
double height = in.nextDouble();
System.out.println("Area: " + width * height);
System.out.println("Perimeter: " + 2 * (width + height));
}
}Width: 4.5
Height: 2
Area: 9.0
Perimeter: 13.0Key takeaway#
Finished this lesson?