Java Fundamentals

Reading Console Input with Scanner

15 min Lesson 6 of 14

Reading Console Input with Scanner

So far every value in your programs has been hard-coded. Real programs need to respond to the user — asking for a name, a number, or a choice. Java provides the Scanner class in the java.util package for exactly this purpose. It wraps any input stream (keyboard, file, network) and lets you pull data out one piece at a time.

Importing and Creating a Scanner

Before using Scanner you must import it, then create an instance connected to System.in — the standard input stream that represents the keyboard.

import java.util.Scanner; public class HelloInput { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter your name: "); String name = scanner.nextLine(); System.out.println("Hello, " + name + "!"); scanner.close(); } }
Always close the Scanner when you are done reading. Calling scanner.close() releases the underlying resource. For simple console programs this matters less, but it is a good habit to build now.

Reading Different Types of Data

Scanner has a family of next…() methods, each matching a Java primitive type:

  • nextLine() — reads the entire line up to and including the newline character, then returns the text without the newline.
  • next() — reads the next token (a sequence of characters separated by whitespace). Stops at a space.
  • nextInt() — reads and parses the next token as an int.
  • nextDouble() — reads and parses the next token as a double.
  • nextBoolean() — reads true or false (case-insensitive).
  • nextLong(), nextFloat() — for larger or single-precision numbers.
import java.util.Scanner; public class ReadNumbers { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter your age: "); int age = scanner.nextInt(); System.out.print("Enter your GPA: "); double gpa = scanner.nextDouble(); System.out.println("Age: " + age + ", GPA: " + gpa); scanner.close(); } }

When you call nextInt() the scanner reads characters until it sees whitespace, converts the text to an int, and returns it. The newline that the user pressed is left in the buffer — this is the source of the most common Scanner pitfall.

The nextLine() Pitfall

Imagine you want to read an integer and then a full line of text:

import java.util.Scanner; public class PitfallDemo { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter your age: "); int age = scanner.nextInt(); // reads "25", leaves "\n" in buffer System.out.print("Enter your city: "); String city = scanner.nextLine(); // immediately reads the leftover "\n" — city is ""! System.out.println("Age: " + age + ", City: " + city); scanner.close(); } }

The program never waits for you to type a city because nextLine() instantly consumed the newline that nextInt() left behind. The fix is to add an extra scanner.nextLine() call right after the numeric read to flush that leftover newline:

import java.util.Scanner; public class PitfallFixed { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter your age: "); int age = scanner.nextInt(); scanner.nextLine(); // flush the leftover newline System.out.print("Enter your city: "); String city = scanner.nextLine(); // now waits for real input System.out.println("Age: " + age + ", City: " + city); scanner.close(); } }
The nextLine() pitfall is the single most common Scanner bug for beginners. Whenever you mix nextInt(), nextDouble(), or any other token-based method with a subsequent nextLine(), add a blank scanner.nextLine() call in between to consume the dangling newline.

Reading Multiple Values in a Loop

A loop combined with Scanner lets you process any number of inputs. A common pattern is to read until the user types a sentinel value — a special input that signals the end:

import java.util.Scanner; public class SumLoop { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); double total = 0; int count = 0; System.out.println("Enter numbers one per line. Type 0 to stop."); double value = scanner.nextDouble(); while (value != 0) { total += value; count++; value = scanner.nextDouble(); } if (count > 0) { System.out.printf("Sum: %.2f Average: %.2f%n", total, total / count); } else { System.out.println("No numbers were entered."); } scanner.close(); } }

Checking Whether Input Is Available

Before calling a read method you can verify that the next token is actually of the expected type using the corresponding has…() method. This prevents a InputMismatchException when the user types text where a number is expected:

import java.util.Scanner; public class SafeRead { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter an integer: "); if (scanner.hasNextInt()) { int number = scanner.nextInt(); System.out.println("You entered: " + number); } else { System.out.println("That is not a valid integer."); } scanner.close(); } }
Prefer hasNextInt() / hasNextDouble() when building interactive programs that must handle bad input gracefully. For quick homework programs or exercises the simple read is fine — but knowing this pattern exists will save you when inputs are unpredictable.

Summary

The Scanner class is your bridge between the keyboard and your program. Remember the key points: import java.util.Scanner, create an instance with new Scanner(System.in), use nextInt() / nextDouble() for numeric input and nextLine() for full-line text, flush the leftover newline after every token-based read that is followed by a nextLine(), and close the scanner when you are done. With this tool you can write interactive programs that respond to real user input — which is the foundation for the console calculator you will build at the end of this tutorial.