A Scanner reads input from the keyboard or a file and breaks it into usable pieces

The Scanner class in Java is a tool that takes text input — whether typed at the keyboard or read from a file — and separates it into individual words, numbers, or lines. Instead of reading one character at a time, Scanner lets you grab whole tokens (a word, a number, a line) in a single command. This saves you from writing extra code to parse the raw text yourself.

When you create a Scanner object, you tell it where to read from: System.in for keyboard input, or a File object for file input. Then you call methods like nextInt(), nextLine(), or next() to pull out the next piece of data in the format you expect. If the input doesn't match what you asked for, Scanner throws an exception and stops.

Key Takeaways

  • Scanner reads input from the keyboard or a file and splits it into tokens you can grab one at a time.
  • Common methods are nextInt() for whole numbers, nextDouble() for decimals, next() for single words, and nextLine() for entire lines.
  • You must import java.util.Scanner at the top of your file before you can use it.
  • Always check whether more input exists using hasNext() or hasNextInt() before calling a read method, or your program will crash.

How to set up a Scanner for keyboard input

To read what a user types, create a Scanner object and pass System.in to its constructor. The import statement must come at the very top of your file, before the class declaration:

import java.util.Scanner;

Then inside your method, write:

Scanner input = new Scanner(System.in);

Now input is a Scanner object ready to read from the keyboard. When you call input.nextInt(), the program pauses and waits for the user to type a number and press Enter. The number is returned as an int that you can store in a variable or use directly.

Reading different types of data with Scanner methods

Scanner offers several methods, each designed for a specific data type. nextInt() reads the next whole number. nextDouble() reads the next decimal number. next() reads the next word (everything up to the next space or line break). nextLine() reads the entire next line, including spaces, and stops at the line break.

The difference between next() and nextLine() matters. If a user types "John Smith" and you call next() twice, the first call returns "John" and the second returns "Smith". If you call nextLine() once, it returns the whole string "John Smith". After calling nextInt(), the number is consumed but the line break is left behind, so the next nextLine() call returns an empty string unless you call nextLine() once to skip it.

You can also use nextBoolean() to read true or false, and nextLong() for very large whole numbers. Each method expects the input to match its type — if you call nextInt() and the user types "hello", Scanner throws an exception.

Checking for input before you read it

The safest way to use Scanner is to check whether the next piece of input exists and matches the type you want before you try to read it. Use hasNext() to check whether any input remains, hasNextInt() to check whether the next token is a number, hasNextDouble() for decimals, and hasNextLine() for lines.

A common pattern is a loop that keeps reading until no more input exists:

while (input.hasNextInt()) {   int number = input.nextInt();   System.out.println(number); }

This loop calls hasNextInt() before each nextInt() call. If the next token is not a number, the loop stops. This prevents your program from crashing when input runs out or doesn't match what you expected.

Reading from a file instead of the keyboard

To read from a file, pass a File object to the Scanner constructor instead of System.in. First import both Scanner and File:

import java.util.Scanner; import java.io.File;

Then create the Scanner like this:

Scanner input = new Scanner(new File("data.txt"));

Now Scanner reads from the file data.txt instead of waiting for keyboard input. The methods work the same way: nextInt(), nextLine(), and the rest all behave identically. The main difference is that when the file ends, hasNext() returns false and your loop stops naturally.

If the file does not exist, Scanner throws an exception. You can catch it with a try-catch block, or declare that your method throws the exception and let the caller handle it.

Common mistakes and how to avoid them

The most common mistake is forgetting to check whether input exists before reading it. Calling nextInt() when no input remains crashes your program with a NoSuchElementException. Always use hasNextInt() or another check first.

Another mistake is mixing next() and nextLine() without understanding the difference. After you call nextInt(), the line break is still in the input stream. If you then call nextLine(), it reads that leftover line break and returns an empty string. To skip it, call nextLine() once with no assignment: input.nextLine();

A third mistake is forgetting to close the Scanner when you are done. Call input.close() at the end of your program to release the resource. This is especially important when reading from files, because an open file can prevent other programs from accessing it.

When to use Scanner and when to use alternatives

Scanner is straightforward and works well for small programs and learning. It is the standard choice for reading keyboard input in introductory Java courses. However, for large files or high-performance applications, other tools like BufferedReader are faster because Scanner does more work behind the scenes to parse and convert data types.

If you only need to read raw text without parsing numbers or splitting into tokens, BufferedReader is a lighter choice. If you need to read structured data like JSON or CSV, specialized libraries handle the parsing for you. But for a homework assignment or a straightforward utility that reads a few numbers or lines, Scanner is the right tool.

Frequently Asked Questions

What happens if I call nextInt() and the user types a word instead of a number?

Scanner throws an exception called InputMismatchException and stops running. The word stays in the input stream unconsumed. To prevent this, always call hasNextInt() before nextInt(), or wrap the read in a try-catch block to handle the exception gracefully.

Why does nextLine() return an empty string after I call nextInt()?

Because nextInt() reads only the number and leaves the line break behind. The next nextLine() call reads that leftover line break and returns an empty string. Call nextLine() once with no assignment right after nextInt() to skip the line break.

Can I use Scanner to read from a website or network connection?

Yes. Scanner can wrap any InputStream, including one from a network socket or URL connection. Create the input stream first, then pass it to the Scanner constructor: Scanner input = new Scanner(urlConnection.getInputStream());

Do I have to close a Scanner when I am done with it?

You should, especially when reading from files. Closing the Scanner releases the underlying resource and prevents file locks or memory leaks. For keyboard input (System.in), closing is less critical but still good practice. Use input.close(); at the end of your program.

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

next() reads the next word (stops at spaces or line breaks). nextLine() reads the entire next line including spaces and stops only at the line break. Use next() to read individual tokens and nextLine() to read a whole sentence or line of input.