Article start
Java Programming: From Zero to Enterprise
1. Java Fundamentals

7. User Input via Scanner

Interacting with users by reading text from the command line.

February 22, 2026·143

[!NOTE] A program isn't very interactive if it only talks to itself. The Scanner class allows your application to pause execution and wait for the user to type something on their keyboard.

Importing and Setting Up Scanner

The Scanner class is not loaded by default to save memory. You must actively import it from the java.util package.

import java.util.Scanner;  // Import the Scanner class

public class Main {
  public static void main(String[] args) {
    // 1. Create a Scanner object hooked up to the System Input stream (keyboard)
    Scanner myObj = new Scanner(System.in);
    
    System.out.println("Enter username:");

    // 2. Pause the program and wait for the user to hit Enter
    String userName = myObj.nextLine(); 
    
    System.out.println("Welcome, " + userName + "!");
    
    // 3. Close the scanner when done!
    myObj.close();
  }
}

[!CAUTION] Always remember to call .close() on your Scanner when your program finishes. Leaving input streams open can cause resource memory leaks.

Reading Different Data Types

The Scanner has different methods corresponding to the primitive data type you want to read.

MethodDescription
.nextLine()Reads a String value (the entire line including spaces).
.nextInt()Reads an int value.
.nextDouble()Reads a double value.
.nextBoolean()Reads a boolean value.

The "Scanner Bug"

  • Newline Artifacts

A very common trap for beginners: If you read an integer, and then immediately try to read a string, it will skip the string! Why? Because nextInt() only reads the number, leaving the "Enter" keypress (newline character) sitting in the buffer. The subsequent nextLine() immediately swallows that newline and finishes.

The Fix: Manually fire a blank nextLine() after reading numbers to clear the buffer.

System.out.println("Enter age:");
int age = scanner.nextInt();

// The Fix! Clear out the leftover 'Enter' key press
scanner.nextLine(); 

System.out.println("Enter name:");
String name = scanner.nextLine(); 

Building Input That Does Not Break Easily

User input is messy. People type spaces, wrong numbers, blank lines, and unexpected words. A beginner program can assume perfect input, but useful programs validate before using input.

Checking Before Reading a Number

Scanner scanner = new Scanner(System.in);

System.out.println("Enter age:");
if (scanner.hasNextInt()) {
    int age = scanner.nextInt();
    System.out.println("Age: " + age);
} else {
    System.out.println("Please enter a valid whole number.");
}

Methods like hasNextInt() let you check whether the next input can be parsed safely. This prevents InputMismatchException.

A Simple Menu Loop

Scanner scanner = new Scanner(System.in);
int choice;

do {
    System.out.println("1. Start");
    System.out.println("2. Help");
    System.out.println("0. Exit");
    choice = scanner.nextInt();
} while (choice != 0);

Common Mistakes

  • Mixing nextInt() and nextLine() without clearing the leftover newline.
  • Closing a Scanner around System.in too early in larger programs.
  • Assuming every user will enter the correct data type.
  • Not showing clear prompts before waiting for input.

Mini Practice

Build a tiny marks calculator. Ask for a name and three marks. Validate numeric input, calculate the average, and print whether the student passed.

Practice Lab: Interactive Marks Calculator

Use Scanner to make your program respond to real input.

  1. Ask for the student's name.
  2. Ask for three marks.
  3. Calculate the average.
  4. Print whether the student passed.
  5. Handle the newline issue after numeric input.

Goal: Practice nextLine(), numeric reads, and clean prompts.

Revision Checkpoint

  • Import: Scanner comes from java.util.
  • nextLine(): Reads a full line including spaces.
  • nextInt(): Reads one integer token.
  • Newline issue: Use an extra nextLine() after numeric reads before reading a full line.
  • Validation: Methods like hasNextInt() help avoid input mismatch errors.

Before the quiz: Explain why nextLine() may appear to skip after nextInt().