Taking Input: Listening to the User

Taking Input: Listening to the User in Java: So far your programs only talk. Now they will listen.

Concept Explanation

So far your programs only talk. Now they will listen. The Scanner class reads what a user types into the console, turning a fixed script into an interactive program.

Scanner lives in java.util, so it must be imported before use.


Syntax or Core Structure

import java.util.Scanner;          // 1. import

public class Greeter {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);   // 2. create

        System.out.print("Your name: ");
        String name = sc.nextLine();           // 3. read text

        System.out.print("Your age: ");
        int age = sc.nextInt();                // 4. read a number

        System.out.printf("Hi %s, next year you turn %d%n", name, age + 1);

        sc.close();                            // 5. release it
    }
}

Reading Methods

MethodReads
nextLine()An entire line, spaces included
next()A single word, stops at whitespace
nextInt()A whole number
nextDouble()A decimal
nextBoolean()true or false

The Classic Scanner Trap

Mixing nextInt() and nextLine() skips input in a way that baffles every beginner:

int age = sc.nextInt();        // reads 25, leaves the newline behind
String city = sc.nextLine();   // instantly consumes that leftover newline -> empty!

nextInt() takes the number but leaves the Enter keypress in the buffer. The next nextLine() swallows it and returns "".

Fix — add a clearing nextLine():

int age = sc.nextInt();
sc.nextLine();                 // discard the leftover newline
String city = sc.nextLine();   // now works correctly

Guarding Against Bad Input

If a user types "abc" into nextInt(), your program crashes with InputMismatchException. Check first:

System.out.print("Enter a number: ");
if (sc.hasNextInt()) {
    int n = sc.nextInt();
    System.out.println("Doubled: " + (n * 2));
} else {
    System.out.println("That was not a number.");
}

Common Mistakes

  1. Forgetting the import: Scanner alone will not resolve without import java.util.Scanner;.
  2. The nextInt/nextLine trap: Described above — the single most common Scanner bug.
  3. System.out instead of System.in: Scanner reads input; out is for printing.

Best Practices

  • One Scanner per program: Create it once in main and pass it around rather than opening several.
  • Prompt with print, not println: The cursor stays on the same line, which reads naturally.
  • Validate with hasNextInt(): Never trust that a user typed what you asked for.

Practice Exercises

  1. The Calculator: Read two numbers and an operator, then print the result.
  2. The Trap Reproduction: Write code that hits the nextInt/nextLine bug, observe the skipped input, then fix it.
  3. The Guarded Reader: Ask for an age and keep re-prompting until hasNextInt() confirms a valid number.