Skip to content

Module 2 · Java Basics — topic 4 of 5

Input with Scanner and Formatted Output

Reading numbers, words and whole lines from the keyboard with Scanner, avoiding the nextInt/nextLine trap, validating input, and formatting output.

Beginner 15 min read·Lesson 7 of 39 in Java Programming

Learning objectives

  • Read numbers, words and lines with Scanner
  • Explain and fix the leftover-newline problem after nextInt
  • Validate input with hasNextInt before reading

Definition

java.util.Scanner reads and parses text from an input source such as System.in, splitting it into tokens separated by whitespace and converting them with methods like nextInt, nextDouble and nextLine.

Introduction

Interactive programs need to ask the user for data. The easiest tool in Java is Scanner, which wraps the standard input stream and turns typed text into numbers and strings. It is used in nearly every beginner program and in every interactive project in this course.

Why it matters

Most beginner bugs with input come from mixing nextInt() and nextLine(); understanding tokens fixes them for good.

Programs that validate input don't crash when someone types abc instead of a number.

Detailed explanation

Create one Scanner for the whole program: Scanner in = new Scanner(System.in);. Creating several on System.in can lose buffered input.

Token methods — next(), nextInt(), nextDouble(), nextBoolean() — skip whitespace, read one token and convert it. If the token isn't of the right type they throw InputMismatchException and leave the token unread.

nextLine() reads everything up to the end of the current line and consumes the newline. Because token methods stop *before* the newline, calling nextLine() right after nextInt() returns an empty string — the rest of the number's line. Fix it by calling in.nextLine() once to discard the remainder, or read every line with nextLine() and parse it yourself.

hasNext methods — hasNextInt(), hasNextLine() and so on — look ahead without consuming anything. Use them to validate input or to read until the input ends (end of file is Ctrl+D on Linux/macOS, Ctrl+Z then Enter on Windows).

Output. System.out.printf and String.format use the same format specifiers: width, precision and flags such as %-10s, %8.2f, %,d (thousands separators) and %05d (zero padding).

For large inputs, BufferedReader with readLine() is faster than Scanner; competitive programmers often use it. Scanner's convenience is perfect for interactive programs.

Syntax

Java
import java.util.Scanner;
Scanner in = new Scanner(System.in);
int age = in.nextInt(); // one token as int
in.nextLine(); // discard the rest of that line
String fullName = in.nextLine(); // a whole line
while (in.hasNextInt()) { int x = in.nextInt(); }
  • next() reads one word; nextLine() reads the whole line.
  • Check hasNextInt() before nextInt() to avoid exceptions.
  • Don't close a Scanner on System.in until the program no longer needs input.

Code examples

Reading two numbers

Java
import java.util.Scanner;
public class Add {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter two numbers: ");
int a = in.nextInt();
int b = in.nextInt();
System.out.println();
System.out.println(a + " + " + b + " = " + (a + b));
}
}
Input
12 30
Output
Enter two numbers: 
12 + 30 = 42

The println after reading starts a fresh line, because typed input isn't part of the program's output.

The nextInt / nextLine trap

Java
import java.util.Scanner;
public class Trap {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int age = in.nextInt();
String rest = in.nextLine(); // the rest of the age line: ""
String name = in.nextLine();
System.out.println("age=" + age + ", rest='" + rest + "', name='" + name + "'");
}
}
Input
20
Asha Rao
Output
age=20, rest='', name='Asha Rao'

More examples

Validating input until the data ends

Java
import java.util.Scanner;
public class Marks {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int count = 0, sum = 0, max = Integer.MIN_VALUE, rejected = 0;
while (in.hasNext()) {
if (in.hasNextInt()) {
int mark = in.nextInt();
if (mark < 0 || mark > 100) { rejected++; continue; }
count++;
sum += mark;
max = Math.max(max, mark);
} else {
System.out.println("skipping '" + in.next() + "'");
rejected++;
}
}
if (count == 0) {
System.out.println("no valid marks");
} else {
System.out.printf("%d marks, average %.2f, highest %d, rejected %d%n", count, (double) sum / count, max, rejected);
}
}
}
Input
78 91 abc 64
105 88 -3 x7
Output
skipping 'abc'
skipping 'x7'
4 marks, average 80.25, highest 91, rejected 4

Step-by-step explanation

  • in.hasNext() is true while any token remains, so the loop processes the whole input regardless of how it is split into lines.
  • hasNextInt() checks the next token without consuming it.
  • Valid integers outside 0–100 are counted as rejected and skipped with continue.
  • Non-numeric tokens must be consumed with in.next(); otherwise hasNextInt() would see the same token forever.
  • The average casts sum to double before dividing: (78 + 91 + 64 + 88) / 4 = 80.25.

Expected output

Running “Validating input until the data ends” with the sample input shown prints exactly:

TextInput
78 91 abc 64
105 88 -3 x7
TextOutput
skipping 'abc'
skipping 'x7'
4 marks, average 80.25, highest 91, rejected 4

Practical applications

  • Menu-driven console applications
  • Reading test data in coding contests
  • Command-line tools that read piped input until end of file

Best practices

  • Create one Scanner per input source and reuse it.
  • Validate with hasNextInt/hasNextDouble before reading numbers from users.
  • Print a prompt with print (no newline) so the user types on the same line.

Common mistakes

Reading a line right after a number

Avoid

int n = in.nextInt();
String name = in.nextLine(); // empty!

Prefer

int n = in.nextInt();
in.nextLine(); // discard rest of line
String name = in.nextLine();

nextInt leaves the newline in the buffer; the next nextLine reads just that newline.

Not consuming an invalid token

Avoid

while (!in.hasNextInt()) System.out.println("try again");

Prefer

while (!in.hasNextInt()) { in.next(); System.out.println("try again"); }

hasNextInt never consumes input, so without in.next() the loop sees the same bad token forever.

Important notes

  • Scanner's number parsing follows the default locale; in locales that use a comma as the decimal separator, nextDouble() expects 3,5. Use new Scanner(System.in).useLocale(java.util.Locale.ROOT) for consistent behaviour.
  • When input is piped from a file, the typed text doesn't appear in the output — only what the program prints does.

Key takeaways

  • Scanner token methods read one whitespace-separated token; nextLine reads the rest of a line.
  • Call nextLine once after nextInt before reading a full line.
  • Use hasNextInt and in.next() to validate and skip bad input.

Try it yourself

  1. 1
    Read a name (full line) and an age, and print a greeting with the age next year.
  2. 2
    Read numbers until end of input and print their count, minimum and maximum.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

2 questions test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerAfter `int n = in.nextInt();`, why does the next `in.nextLine()` return an empty string?
  • BeginnerWhat is printed?
Practise this topic