Most beginner programs need to ask the user something: a name, a number of items, a list of marks. In Java the usual tool is Scanner from java.util. It reads text from the keyboard, a file or a string and breaks it into numbers, words and lines. This lesson shows the main Scanner methods, how to handle wrong input safely, and the famous nextInt() then nextLine() trap.
In this lesson you will learn
- Creating a
Scannerfor keyboard input nextLine,next,nextIntandnextDouble- Why
nextLine()afternextInt()returns an empty string - Checking input with
hasNextIntbefore reading - Reading until the input ends
You should know variables, loops and wrapper classes.
Reading Values
A real program reads from the keyboard with new Scanner(System.in). In these examples the “typed” input comes from a string instead, so you can see exactly what was entered and the output is always the same. The Scanner methods behave identically either way.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// In a real program: Scanner in = new Scanner(System.in);
// Here the "keyboard input" comes from a String so the output is repeatable.
// (A real program would print a prompt such as "Name: " before each read.)
String typed = "Nusrat\n21 3.82\nyes\n";
Scanner in = new Scanner(typed);
String name = in.nextLine(); // whole line
int age = in.nextInt(); // next token as int
double cgpa = in.nextDouble(); // next token as double
in.nextLine(); // consume the rest of that line
boolean wants = in.next().equalsIgnoreCase("yes");
System.out.printf("%s (%d) has CGPA %.2f, scholarship: %b%n", name, age, cgpa, wants);
in.close();
// The classic trap: nextInt() leaves the line break behind
Scanner trap = new Scanner("25\nRafi\n");
int qty = trap.nextInt();
String leftover = trap.nextLine(); // reads the empty rest of "25" line
String customer = trap.nextLine();
System.out.println("qty=" + qty + ", leftover=[" + leftover + "], customer=[" + customer + "]");
}
}
Output
Nusrat (21) has CGPA 3.82, scholarship: true
qty=25, leftover=[], customer=[Rafi]
Scannersplits input into tokens separated by whitespace (spaces, tabs and line breaks).nextLine()reads everything up to the end of the line, so it can read names with spaces such as “Nusrat Jahan”.nextInt()andnextDouble()read the next token and convert it.next()reads one word.- The trap:
nextInt()reads “25” but leaves the line break after it. The nextnextLine()reads that empty remainder, soleftoveris""and the customer name is read only by the second call. Calling an extranextLine()after reading numbers, as in the first part of the example, fixes it. printfformats the result:%stext,%dwhole number,%.2ftwo decimals,%bboolean,%nnew line.
Validating Input and Reading Until the End
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// The user types: a number of marks, then the marks, with one mistake
Scanner in = new Scanner("5\n78 92 abc 64\n85 70\n");
int n = in.nextInt();
int total = 0, read = 0;
while (read < n && in.hasNext()) {
if (in.hasNextInt()) { // check before reading
total += in.nextInt();
read++;
} else {
System.out.println("Skipping invalid input: " + in.next());
}
}
System.out.printf("Read %d marks, average %.1f%n", read, (double) total / read);
// Reading line by line until the input ends
Scanner lines = new Scanner("Dhaka 22\nKhulna 18\n\nSylhet 25\n");
int lineNo = 0;
while (lines.hasNextLine()) {
String line = lines.nextLine().trim();
lineNo++;
if (line.isEmpty()) continue;
String[] parts = line.split(" ");
System.out.println(lineNo + ": " + parts[0] + " -> " + Integer.parseInt(parts[1]) + " C");
}
}
}
Output
Skipping invalid input: abc
Read 5 marks, average 77.8
1: Dhaka -> 22 C
2: Khulna -> 18 C
4: Sylhet -> 25 C
- If the user types “abc” where a number is expected,
nextInt()throwsInputMismatchException. CheckinghasNextInt()first lets the program skip the bad token withnext()and carry on. - The loop stops once five valid marks have been read. The bad token does not count toward the five, so all five numbers are still collected.
(double) total / readconverts before dividing, so the average keeps its decimals (77.8).hasNextLine()is true while there is more input, which is how you read a whole file or piped input line by line. The empty third line is skipped withcontinue.- Splitting each line and parsing the parts is a common pattern for simple data such as “city temperature”.
Scanner Methods
| Method | Reads |
|---|---|
nextLine() | The rest of the current line |
next() | The next word (token) |
nextInt(), nextLong(), nextDouble(), nextBoolean() | The next token as a number or boolean |
hasNext(), hasNextInt(), hasNextLine() | Check whether such input is available |
useDelimiter(",") | Split tokens on a different separator |
close() | Release the input source |
To read a file, pass a Path or File: new Scanner(Path.of("marks.txt")). See Java file handling. For very large inputs, BufferedReader is faster than Scanner.
Common Mistakes
- Mixing
nextInt()andnextLine()without consuming the leftover line break. - Not checking
hasNextInt(), so one typing mistake crashes the program. - Creating a new
Scanner(System.in)in every method. Create one and pass it around. - Closing a
ScanneronSystem.intoo early; that also closesSystem.in, and later reads fail.
Practice Exercises
Exercise 1. Keep asking for a number between 1 and 10 until the user enters a valid one.
Show answer
Scanner in = new Scanner(System.in);
int n = -1;
while (n < 1 || n > 10) {
System.out.print("Enter 1-10: ");
if (in.hasNextInt()) n = in.nextInt();
else in.next(); // discard the bad token
}
System.out.println("You chose " + n);
Exercise 2. Read comma-separated prices from the string "120,45.5,300" and print their total.
Show answer
Scanner in = new Scanner("120,45.5,300").useDelimiter(",");
double total = 0;
while (in.hasNextDouble()) total += in.nextDouble();
System.out.println(total); // 465.5
Frequently Asked Questions
Why does nextDouble() fail on “3.5” on some computers?
Scanner uses the computer’s locale, and some locales write decimals with a comma. Call in.useLocale(Locale.US) so a dot is always the decimal separator.
Should I close a Scanner?
Close scanners on files and strings when you are done, ideally with try-with-resources. A scanner on System.in is usually left open until the program ends.
Summary
new Scanner(System.in)reads keyboard input.- Use
nextLine()for whole lines andnextInt()/nextDouble()for numbers. - Consume the leftover line break after reading numbers.
- Check with
hasNextInt()and friends before reading.
