Skip to content
Tutorials Center
My learning

Topics

Lesson 6 of 201 ยท Getting Started

Reading User Input

Read keyboard input in Java with Scanner, IO.readln (Java 25) and BufferedReader. Parse numbers safely, avoid the nextInt + nextLine trap and loop over all input.

A program that only prints is a monologue. Once it can read input, it becomes a conversation: it can ask for a name, a number of items or a command, and react to the answer. In Java, input typed at the keyboard arrives through standard input, available as System.in, and you read it with one of three tools: IO.readln, the Scanner class, or a BufferedReader.

This lesson covers all three, how to turn text into numbers, the most famous input bug in Java (the nextInt + nextLine trap), and how to validate input and read until there's nothing left.

Using the Input box

On your own computer, a program waiting for input pauses until you type a line and press Enter. Our editor runs your program on a server, so you type the input in advance in the Input box under the code. Each line in the box is one line the user "typed". The examples in this lesson come with input already filled in, so pressing Run just works. Change the input and run again to see how the program reacts.

Two details to know:

  • The input itself isn't echoed in the output. A prompt like Name? is followed directly by whatever the program prints next. In a real terminal you would see your typing there.
  • If the program asks for more lines than the box contains, it reaches the end of input. Each tool reacts differently, as you'll see below.

The simplest way: IO.readln

Java 25 added IO.readln, the input partner of IO.println. It prints an optional prompt, waits for the user, and returns the whole line as a String:

Java Asking two questions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

  • IO.readln("prompt") prints the prompt without a line break, so the cursor waits on the same line, and then reads one line.
  • IO.readln() with no argument reads a line without a prompt.
  • The returned string doesn't include the line break at the end.
  • At the end of input, IO.readln returns null instead of a string. Try deleting the second line of the Input box: the greeting then says from null.

IO.readln is perfect for short programs, but it needs Java 25 and only reads whole lines. For everything else, including most code you'll see in the wild, Java developers use Scanner.

Reading with Scanner

Scanner (in java.util) reads input and can split it into pieces called tokens: words and numbers separated by whitespace. You create one Scanner for System.in at the start of the program and then call its methods:

Java Scanner basics

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The most useful Scanner methods:

Method Reads Returns
nextLine() the rest of the current line String (without the line break)
next() the next token (word) String
nextInt() the next token, as a whole number int
nextLong(), nextDouble(), nextBoolean() the next token, converted long, double, boolean
hasNextLine(), hasNext(), hasNextInt(), hasNextDouble() nothing, they only look ahead boolean: is there such input waiting?

Token methods skip any whitespace, including line breaks, so nextInt() will happily read a number from the next line. They also accept several values on one line: if the user types 3 4 5, three calls to nextInt() return 3, 4 and 5.

When input doesn't match what you asked for, Scanner throws an exception. If the user types twelve where nextInt() expects a number, you get an InputMismatchException. If the input runs out, you get a NoSuchElementException. You'll learn to prevent both with hasNext... checks below.

Note: In a compact source file, Scanner works without the import, because compact files import the whole java.base module. In a normal class, write import java.util.Scanner; at the top. Also, nextDouble() follows the computer's locale: on a computer set to German or French it expects 1,82 instead of 1.82. Call in.useLocale(Locale.ROOT) if your program must always accept a dot.

The nextInt + nextLine trap

This is the input bug almost every Java learner hits. Run the program and look at the name it prints:

Java The trap (has a bug on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The name comes out empty: Name: []. Here's why. The user typed 36 and pressed Enter, so the input contains 36 followed by a line break. nextInt() reads the number 36 and stops right before the line break. Then nextLine() reads "the rest of the current line", which is nothing at all, and returns an empty string. The real name is never read.

There are two standard fixes:

  1. Consume the leftover line break. Call in.nextLine(); once right after nextInt(), throwing away the empty rest of the line.
  2. Read every line with nextLine() and convert numbers yourself with Integer.parseInt(...). This avoids the problem entirely, and it's the approach many professionals prefer.

Here's the program fixed with the second approach:

Java The trap, fixed

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Converting text to numbers

Input always arrives as text. To calculate with it, convert it with a parse method:

Method Converts "..." to Example
Integer.parseInt(s) int Integer.parseInt("42") gives 42
Long.parseLong(s) long for very large whole numbers
Double.parseDouble(s) double Double.parseDouble("2.5") gives 2.5
Boolean.parseBoolean(s) boolean true only for "true", ignoring case; anything else is false

Parse methods are strict. Text that isn't a valid number throws a NumberFormatException, and that includes surrounding spaces, which is why the example above calls strip() first:

Java Parsing numbers (the last line fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The program prints the quantity, price and total (the long 839.5799999999999 is the floating-point rounding you met in Printing Output; printf("%.2f", ...) would show 839.58), then stops with java.lang.NumberFormatException: For input string: "abc". The message quotes the exact text that failed, which makes these errors easy to track down. Later, in Exceptions and try-catch, you'll catch this exception and ask the user again instead of crashing. More conversions are covered in Type Casting and Conversion.

Validating input with hasNextInt

Users make typos. Scanner's hasNext... methods let you check what's coming before you read it, so a bad value never causes an exception. This loop keeps asking until it gets a valid number in range:

Java Ask until the answer is valid

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

This program uses a while loop, if, continue and break, which you'll study properly in while and do-while Loops. The important idea for now: hasNextInt() only peeks at the input. If it says the next token isn't a number, you must remove that token with next(); otherwise the loop would look at the same bad token forever.

Reading until the input ends

Sometimes you don't know how many values are coming: a list of scores, a file of lines, a stream of commands. Loop while hasNext... returns true, and the loop ends naturally when the input runs out:

Java Sum every number in the input

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The numbers can be spread over any number of lines, because token methods skip line breaks. Use while (in.hasNextLine()) with nextLine() instead when each line matters, for example when reading commands.

BufferedReader: fast, line-based input

Before Scanner existed, Java programs read input with a BufferedReader wrapped around System.in. It's still common, especially in competitive programming and in code that processes large amounts of text, because it's considerably faster than Scanner on big inputs:

Java Reading lines with BufferedReader

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

  • readLine() returns the next line without its line break, or null at the end of input (the last line of output shows that).
  • It only reads lines. Converting numbers is up to you, with the parse methods above.
  • It can throw an IOException, a checked exception, so the method has to declare throws IOException or handle it. Throwing Exceptions explains what that means.

Which one should you use?

Tool Best for Watch out for
IO.readln short programs, prompts, learning (Java 25+) lines only; returns null at the end
Scanner mixed words and numbers, validation with hasNext... the nextInt + nextLine trap; slower on huge inputs
BufferedReader large inputs, line-by-line processing lines only; throws IOException

Whichever you choose, follow two rules:

  • Use one reader for all input. Scanner and BufferedReader read ahead into a private buffer, so mixing two readers on System.in, or mixing either one with IO.readln, can make one of them miss lines that the other already grabbed.
  • Don't close a Scanner that wraps System.in. Closing it closes System.in itself, and no other code in the program can read input afterwards. It's normal to leave it open; the program's exit cleans up. (For files, which you'll read in Reading and Writing Files, closing is essential.)

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. The Input box contains 25 on line 1 and Sam on line 2. What does name hold after int age = in.nextInt(); String name = in.nextLine();?

    nextInt() stops before the line break after 25, so nextLine() returns the empty rest of line 1. Call nextLine() once more, or read every line with nextLine() and parse it.
  2. 2. What does Integer.parseInt(" 7") do?

    Parse methods don't allow surrounding spaces. Call strip() (or trim()) first, as in Integer.parseInt(text.strip()).
  3. 3. What does IO.readln() return when there is no more input?

    IO.readln() and BufferedReader.readLine() return null at the end of input. Scanner's nextLine() throws a NoSuchElementException instead.
  4. 4. In a validation loop, hasNextInt() returns false. Why must you call in.next() before asking again?

    The hasNext... methods never consume input. Without next(), the same invalid token is checked again on every loop iteration, forever.
  5. 5. The Input box contains 4 8 on line 1 and 15 on line 2. What does the sum-every-number loop (while (in.hasNextInt())) print as the sum?

    Token methods like nextInt() skip whitespace, including line breaks, so the loop reads 4, 8 and 15 and stops when no input is left.

Summary

  • Keyboard input arrives on standard input, System.in. In our editor, put it in the Input box, one line per typed line.
  • IO.readln("prompt") (Java 25) prints a prompt and returns one line, or null at the end of input.
  • Scanner reads lines (nextLine) and tokens (next, nextInt, nextDouble); hasNext... methods peek without reading.
  • nextInt() leaves the line break behind, so a following nextLine() returns "". Consume it, or read lines and parse them.
  • Convert text with Integer.parseInt, Double.parseDouble and friends; invalid text (even extra spaces) throws NumberFormatException.
  • BufferedReader.readLine() is fast and line-based; it returns null at the end and declares IOException.
  • Use one reader for all input, and don't close a Scanner on System.in.

Next: Java Keywords and Identifiers, where you'll learn which words Java reserves for itself and the exact rules for naming things.