Taking input with Scanner

So far every value was written into the code. Real programs ask the user. In Java, the classic way to read what someone types is the Scanner class. In this lesson you'll read numbers and text, see the hidden input buffer that explains the famous “nextLine is skipped” bug, and learn to handle wrong input without crashing.

Module 2 · Language Basics⏱ 17 minBeginnerUses keyboard input8 practice problems
1 The story

The skipped question

Riya builds a canteen kiosk program. It asks for the number of cups, then the customer's name. But after she types 3 and presses Enter, the program doesn't wait for the name: it prints the bill with a blank name. She runs it again. Same thing.

Enter Keyboard Input buffer (System.in) 3 \n nextInt() takes this …nextLine() takes this: "" cups = 3 name = "" your variables myphatshala.in
Riya

Sir, my program skips the name question. I'm definitely calling nextLine()!

Arjun Sir

When you typed 3 and pressed Enter, two things went into the input buffer: the character 3 and an invisible newline. nextInt() took only the 3. The newline was still waiting, so nextLine() found a complete (empty) line straight away.

Riya

So it didn't skip the question; it answered it with nothing!

Arjun Sir

Exactly. Once you can see the buffer, Scanner stops being mysterious. Let's look inside.

2 Definition

What is Scanner?

Formal definition (write this in exams)

java.util.Scanner is a class that breaks input into tokens separated by a delimiter (whitespace by default) and converts them into primitive values or Strings using methods such as nextInt(), nextDouble(), next() and nextLine(). To read from the keyboard, a Scanner is created on the standard input stream: new Scanner(System.in).

In simple words

What you type goes into a waiting area called the input buffer. Scanner reads from it piece by piece: a number, a word or a whole line, whichever you ask for. Whatever it doesn't take stays in the buffer for the next read.

Words you'll meet in this lesson

System.inThe standard input stream: the bytes typed on the keyboard (or piped from a file).
BufferMemory where typed characters wait until the program reads them.
TokenA piece of input between separators, like Riya or 20 in Riya 20.
DelimiterWhat separates tokens: spaces, tabs and newlines by default.
NewlineThe invisible character Enter adds: \n (Windows sends \r\n).
BlockingWhen a read waits until the user types something.

Scanner methods at a glance

MethodReadsInput Riya Sharma⏎ gives
next()One token (a word)"Riya"
nextLine()The rest of the line, without the newline"Riya Sharma"
nextInt()One token as an intInputMismatchException (not a number)
nextDouble(), nextLong(), nextBoolean()One token as that typeSame rule as nextInt
hasNextInt(), hasNext(), hasNextLine()Checks without readingfalse for hasNextInt

Exam tip: Scanner is in java.util, so you must write import java.util.Scanner;. next() reads one word; nextLine() reads a whole line. After nextInt(), call an extra nextLine() to clear the leftover newline before reading a line.

3 Types and ways to use it

Ways to read input in Java

Scanner

Easy and flexible: reads ints, doubles, words and lines, and can read from the keyboard, a String or a file. Slower for huge inputs.

Learning, small tools

BufferedReader

new BufferedReader(new InputStreamReader(System.in)). Reads whole lines fast; you parse numbers yourself with Integer.parseInt.

Large input, contests

Command-line arguments

java Main Riya 20 → args[0], args[1]. No typing during the run; good for scripts and scheduled jobs.

Automation

Real applications

Web and mobile apps don't read the keyboard directly: input arrives as HTTP requests, form fields, files or messages, but parsing and validating it works the same way.

Production

Scanner can read from more than the keyboard

SourceCreate it with
Keyboardnew Scanner(System.in)
A Stringnew Scanner("10 20 30")
A filenew Scanner(Path.of("marks.txt")) (Module 13)
4 Step by step

Reading input, one step at a time

  1. Import Scanner

    import java.util.Scanner;
    Without this line javac reports “cannot find symbol: class Scanner”. The import only tells javac the full name; no code is copied.
  2. Create one Scanner on System.in

    Scanner sc = new Scanner(System.in);
    A Scanner object is created on the heap. It wraps the standard input stream and keeps its own buffer of characters that haven't been used yet.
  3. Prompt, then read

    System.out.print("Cups of chai: ");
    int cups = sc.nextInt();
    Use print (not println) so the cursor stays on the prompt line. nextInt() blocks: the program waits until a line is entered, then skips whitespace, reads digits and converts them to an int.
  4. Clear the newline before reading a line

    sc.nextLine();                 // throw away the leftover newline
    System.out.print("Name: ");
    String name = sc.nextLine();
    nextInt stops right after the digits. The newline stays in the buffer. The extra nextLine() consumes it, so the next one waits for real input.
  5. Validate, and close when done

    while (!sc.hasNextInt()) {
        System.out.print("Please enter a number: ");
        sc.next();                 // discard the bad token
    }
    int age = sc.nextInt();
    sc.close();
    hasNextInt() looks at the next token without removing it. Closing a Scanner on System.in also closes System.in itself, so do it only once, at the very end.
5 See it happen

The input buffer: both views

Left: the console. Right: the characters waiting in Scanner's buffer, and what each method takes.

Riya's kiosk program 6 steps
What you see ▌ (blinking cursor, nothing printed yet) Name: Riya Sharma⏎ Cups: 3⏎ Note for the cook: Bill for Riya Sharma: 3 cups, note "" Cups: three⏎ Exception in thread "main"java.util.InputMismatchException Scanner sc = new Scanner(System.in); The user types a full name and presses Enter. nextLine() returns "Riya Sharma". nextInt() returns 3. The note question didn't wait at all! Letters where a number was expected. myphatshala.in
Behind the screen Scanner's buffer (empty: nextLine() is blocking, waiting) R i y a ␣ S h a r m a\n R i y a ␣ S h a r m a\n 3\n 3 \n t h r e e\n Nothing has been typed yet.The read blocks: the program pauses here. Enter sends the line into the buffer,including the invisible newline \n.Green marker = Scanner's read position. nextLine() takes everything up to \n,consumes the \n too, and returns the text without it.The buffer is empty again. nextInt() skips spaces, reads the token "3"and stops right after it.The \n is still in the buffer! nextLine() sees “end of line” immediately,so it returns "" without waiting.Fix: call sc.nextLine() once after nextInt(). nextInt() finds the token "three",which isn't an int. It throws, and the bad tokenstays in the buffer. Check first with hasNextInt(). myphatshala.in
6 Real-world use

Reading input in real software

Production systems rarely read the keyboard, but they constantly read and validate input. The lessons from Scanner carry over directly.

Watch it with an example: the nextInt() then nextLine() trap

A kiosk asks for age, then name. The user types 21 Enter Riya Enter, but the name comes out empty. Watch Scanner's input buffer to see why.

What Scanner leaves behind 6 steps
Animated example // user types: 21⏎Riya⏎ int age = sc.nextInt(); String name = sc.nextLine(); // name is "" (empty!) sc.nextLine(); // eat the leftover ⏎ String name = sc.nextLine(); input buffer 2 2 1 1 ⏎ ⏎ R R i i y y a a ⏎ ⏎ age = 21 name = "" name = "Riya" nextInt() reads the digits and stops before ⏎ nextLine() reads up to the next ⏎: nothing! an extra nextLine() throws the old ⏎ away now nextLine() gets the real name myphatshala.in
$ ./backup-toolContinue? (y/n)y

1. Command-line tools for developers and ops

Small internal tools (database migration helpers, admin utilities, installers) ask questions in the terminal and read answers just like a Scanner program.

Prompt→read + validate answer→Run the task
Test case input5 / 3 1 4 1 5

2. Online coding tests and contests

Campus hiring tests and platforms like HackerRank feed test input through standard input. Reading it correctly, and fast enough, is the first step of every solution.

stdin test file→Scanner / BufferedReader→Your output is compared
“abc” is not a number

3. Validating form input

An age field, a PIN code or an amount typed into a web form arrives as text. The server checks it's a valid number in range before using it, the same idea as hasNextInt().

"abc" in age field→validate before parsing→Friendly error message
,

4. Parsing files line by line

Reading a CSV of student marks or a log file uses the same token/line ideas: read a line, split by a delimiter, convert each piece (Module 13).

marks.csv→line → split(",") → parseInt→Report
echo "3" |java Main

5. Automated tests of console programs

Because System.in is just a stream of bytes, input can come from a file or a pipe instead of a person, which is how console programs are tested automatically.

input.txt→java Main < input.txt→Compare output

Examples are simplified. Production systems use frameworks for input, but the parsing ideas are the same.

7 Run the code

Riya's kiosk, fixed

In the live editor, type the input into the STDIN / input box before pressing Run. Each challenge's hint shows sample input.

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Cups of chai: ");
        int cups = sc.nextInt();
        sc.nextLine();                          // clear the leftover newline
        System.out.print("Name: ");
        String name = sc.nextLine();
        System.out.print("Price per cup: ");
        double price = sc.nextDouble();
        System.out.println(name + ", your bill is Rs " + (cups * price));
        sc.close();
    }
}
Cups of chai: 3 Name: Riya Sharma Price per cup: 20 Riya Sharma, your bill is Rs 60.0

The console shows your typed input (3, Riya Sharma, 20) next to each prompt.

  • import java.util.Scanner;Scanner lives in the java.util package.
  • new Scanner(System.in)One Scanner reading from the keyboard. Create it once and reuse it.
  • System.out.print("…")print keeps the cursor on the same line, so the answer appears next to the question.
  • sc.nextLine();The fix for the trap: consumes the newline left by nextInt().
  • sc.nextDouble()Reads a decimal number. Typing 20 is fine; it becomes 20.0.
  • sc.close();Closes the Scanner and System.in. Do it once, at the end.
8 Line by line

Watch the buffer drain

The input for this run is 3⏎Riya Sharma⏎20⏎. The note on each step shows what is left in Scanner's buffer.

Worked examples: real problems, solved and traced in memory

Real programs read input. Each program below reads from the keyboard with Scanner; the trace and the runner feed it the sample input shown. Watch each next…() call take the next piece of input and store it in a variable.

Example 1Grocery · billing

Read an item, quantity and price

Problem statement

A grocery counter types the item name, quantity and unit price. Print a bill line with the amount.

Input
Basmati Rice
3
92.50
Expected output
Basmati Rice x3 = Rs 277.5

Approach

  1. nextLine() reads the whole first line (names can have spaces).
  2. nextInt() and nextDouble() read numbers.
  3. Multiply and print.

Solution: run it live

What happens in memory, step by step

Recorded from the real JVM: press Next to execute one line at a time. Watch method calls push and pop frames on the stack, and objects (numbered #1, #2 …) appear on the heap.

Example 2Education · marks

Average of three subjects

Problem statement

A teacher enters a student's name and three marks on one line. Print the total and the average with one decimal.

Input
Ravi 78 85 91
Expected output
Ravi: total 254, average 84.7

Approach

  1. next() reads one word.
  2. Three nextInt() calls read the marks from the same line.
  3. printf("%.1f") shows one decimal.

Solution: run it live

What happens in memory, step by step

Recorded from the real JVM: press Next to execute one line at a time. Watch method calls push and pop frames on the stack, and objects (numbered #1, #2 …) appear on the heap.

Example 3Banking · forms

The nextInt + nextLine trap

Problem statement

A bank form reads an account number (a number) and then the holder's full name (a line). Read naively, the name comes out empty, because nextInt() leaves the Enter key in the input. Show the fix: an extra nextLine().

Input
40021876
Asha Kumari Verma
Expected output
Account: 40021876
Leftover was []
Holder: Asha Kumari Verma

Approach

  1. nextInt() reads 40021876 but not the line break after it.
  2. One nextLine() consumes that leftover line break.
  3. The next nextLine() reads the real name.

Solution: run it live

What happens in memory, step by step

Recorded from the real JVM: press Next to execute one line at a time. Watch method calls push and pop frames on the stack, and objects (numbered #1, #2 …) appear on the heap.

9 Quiz and revision

Check yourself

Quick revision

Lesson 2.6 in one screen

  • import java.util.Scanner; → Scanner sc = new Scanner(System.in);
  • nextInt(), nextDouble(), next() read one token; nextLine() reads the rest of the line.
  • Typed input waits in a buffer; reads block until input arrives.
  • The trap: nextInt() leaves \n; call sc.nextLine() once before reading a line.
  • Bad input → InputMismatchException; validate with hasNextInt().
  • Use one Scanner; close it once at the end (it closes System.in).
  • For huge inputs, BufferedReader + Integer.parseInt is faster.

Interview and viva questions

What is the difference between next() and nextLine()?

next() skips leading whitespace and returns the next token, stopping at whitespace. nextLine() returns everything up to the end of the current line (which may be empty) and consumes the line terminator.

Why does nextLine() get skipped after nextInt()?

nextInt() reads only the number and leaves the newline in the buffer. The following nextLine() reads the remainder of that line, which is empty. Fix it by calling an extra nextLine() after nextInt(), or by reading every line with nextLine() and parsing it yourself.

Scanner vs BufferedReader?

Scanner is convenient: it parses ints, doubles and tokens, and works with many sources. BufferedReader is faster because it reads large blocks and only returns lines, leaving parsing to you. BufferedReader's readLine also throws IOException, which must be handled.

Is Scanner thread-safe?

No. A Scanner should be used by one thread at a time. Console input in multi-threaded programs is usually read by a single thread.

What is System.in?

A static field of the System class: an InputStream connected to the program's standard input, which is the keyboard by default but can be redirected from a file or another program.

Practice problems

Read input with Scanner and compute something with it. Each problem's sample input is used when you run it. The last three are business tasks.

P1Easy

Greet by name

Read a name and print "Hello, NAME!".

Input
Meena
Expected output
Hello, Meena!
Show solution and explanation
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String name = sc.nextLine();
        System.out.println("Hello, " + name + "!");
    }
}
Hello, Meena!

How it works: nextLine reads the whole line typed.

P2Easy

Sum of two numbers

Read two integers and print their sum.

Input
25 17
Expected output
42
Show solution and explanation
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int a = sc.nextInt(), b = sc.nextInt();
        System.out.println(a + b);
    }
}
42

How it works: nextInt skips spaces and reads one number at a time.

P3Easy

Square of a decimal

Read a decimal number and print its square.

Input
2.5
Expected output
6.25
Show solution and explanation
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        double x = sc.nextDouble();
        System.out.println(x * x);
    }
}
6.25

How it works: nextDouble reads numbers with decimals.

P4Medium

Rectangle from input

Read length and width, print area and perimeter.

Input
12 7
Expected output
Area 84, perimeter 38
Show solution and explanation
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int l = sc.nextInt(), w = sc.nextInt();
        System.out.println("Area " + l * w + ", perimeter " + 2 * (l + w));
    }
}
Area 84, perimeter 38

How it works: read once, use many times.

P5Medium

Number then sentence

Read a roll number, then a full name on the next line, and print both.

Input
17
Kiran Rao
Expected output
17: Kiran Rao
Show solution and explanation
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int roll = sc.nextInt();
        sc.nextLine();
        String name = sc.nextLine();
        System.out.println(roll + ": " + name);
    }
}
17: Kiran Rao

How it works: the extra nextLine() eats the line break left by nextInt.

P6Business problem

Bill with GST from input

Read an amount and print the GST (18%) and total.

Input
1250
Expected output
GST: Rs 225.0, total: Rs 1475.0
Show solution and explanation
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        double amount = sc.nextDouble();
        double gst = amount * 0.18;
        System.out.println("GST: Rs " + gst + ", total: Rs " + (amount + gst));
    }
}
GST: Rs 225.0, total: Rs 1475.0

How it works: the same program now works for any amount typed in.

P7Business problem

Fuel bill

Read litres and price per litre; print the bill rounded to the rupee.

Input
23.5 104.7
Expected output
Pay Rs 2460
Show solution and explanation
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        double litres = sc.nextDouble(), rate = sc.nextDouble();
        System.out.println("Pay Rs " + Math.round(litres * rate));
    }
}
Pay Rs 2460

How it works: 23.5 × 104.7 = 2460.45, rounded to 2460.

P8Business problem

Customer details card

Read a customer's name (line), age and city, then print a one-line card.

Input
Asha Verma
29 Pune
Expected output
Asha Verma (29), Pune
Show solution and explanation
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String name = sc.nextLine();
        int age = sc.nextInt();
        String city = sc.next();
        System.out.println(name + " (" + age + "), " + city);
    }
}
Asha Verma (29), Pune

How it works: nextLine for the full name first avoids the leftover-line-break problem.

Real-world scenario questions (asked in company interviews)

Input handling is where programs meet the messy real world. Decide your answer first, then open the model answer.

Campus hiring · coding testFresher

Correct answer, but “Time Limit Exceeded”

In an online test, your solution passes small test cases but fails the big ones with Time Limit Exceeded. The big input has 10 lakh numbers. Your algorithm is O(n). You read input with Scanner.nextInt() in a loop. What would you try first?

The interviewer is checking: do you know that input reading itself can be the bottleneck, and what the faster alternatives are?

Show a strong answer

With an O(n) algorithm, input reading is the likely bottleneck. Scanner parses every token with regular expressions, which is slow for millions of tokens.

  • Switch to BufferedReader: read lines, split them (or use StringTokenizer) and convert with Integer.parseInt.
  • For very large inputs, use a DataInputStream-based fast reader or StreamTokenizer.
  • Also batch output: build it in a StringBuilder and print once, rather than calling println lakhs of times.

Avoid: rewriting the algorithm first without checking where the time is going.

Internal tool · bug reportFresher

NoSuchElementException on the second menu

A console admin tool has two methods, readUserDetails() and readPermissions(). Each creates its own Scanner(System.in) and closes it at the end, “to be tidy”. The first works; the second immediately throws NoSuchElementException: No line found. Why?

The interviewer is checking: do you understand that closing a Scanner closes the stream it wraps?

Show a strong answer

Closing the first Scanner also closed System.in. The second Scanner wraps a closed stream, so there's nothing left to read.

  • Create one Scanner for System.in (for example in main) and pass it to the methods that need it.
  • Close it once, when the program finishes (or not at all for System.in in small tools).
  • Tidiness rule: close resources you opened, like files. System.in was opened by the JVM.

Avoid: catching the exception and creating yet another Scanner.

Banking · ATM simulatorFresher

The program crashes when a user types a letter

During a demo of a training ATM simulator, a tester typed “5oo” instead of 500 for the withdrawal amount and the program crashed with a stack trace. The client was not impressed. How would you make input handling robust?

The interviewer is checking: do you validate input instead of assuming users type correctly?

Show a strong answer
  • Never call nextInt() blindly. Check with hasNextInt() and discard bad tokens with next(), or read the whole line and parse it inside a try-catch for NumberFormatException.
  • Validate the range and rules too: positive, a multiple of 100, within the daily limit.
  • Show a clear message and ask again, instead of exiting.
  • Add tests with empty input, letters, negative numbers and huge numbers.

Avoid saying: “Users should type correctly.” Assume every input can be wrong.

Product company · data import1–3 years

Works on your laptop, fails on the European server

A small import job reads prices like 19.5 from a file with scanner.nextDouble(). It runs fine in India, but on a server configured with a German locale, it throws InputMismatchException on every price. What's going on?

The interviewer is checking: do you know that Scanner's number parsing depends on the default locale?

Show a strong answer

Scanner uses the machine's default locale to parse numbers. In a German locale, the decimal separator is a comma (19,5), so 19.5 isn't recognised as a number.

  • For machine-generated data, fix the locale explicitly: scanner.useLocale(Locale.ROOT), or read the text and use Double.parseDouble, which always expects a dot.
  • Keep user-facing formatting (display) locale-aware, but parsing of data files locale-independent.
  • Add a test that runs with a different default locale.

Avoid: “Change the server's locale.” The code should not depend on it.