User Input

Java · Lesson 8 of 32 7 min read Updated

So far your programs have printed fixed values. Real programs ask questions: your name, how many tickets, which option from a menu. In this lesson you will read input typed on the keyboard with the Scanner class, fix the most common Scanner bug, check that the user really typed a number, and pass values on the command line.

You will also see the shorter IO.readln method that Java 25 added for simple console programs.

Reading input with Scanner

Scanner lives in the package java.util, so you import it at the top of the file. You create one Scanner connected to System.in (the keyboard) and then call its methods to read values:

MethodReads
nextLine()the whole line, including spaces, as a String
next()one word (up to the next space)
nextInt()a whole number as an int
nextDouble()a decimal number as a double
nextBoolean()true or false
Java
import java.util.Scanner;

public class Welcome {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);

        System.out.print("Your name: ");
        String name = in.nextLine();

        System.out.print("Your city: ");
        String city = in.nextLine();

        System.out.print("Your age: ");
        int age = in.nextInt();

        System.out.println("Hello " + name + " from " + city + "!");
        System.out.println("In 5 years you will be " + (age + 5) + ".");
    }
}

When you run it, the terminal looks like this (the text after each prompt is what the user typed):

Output
Your name: Isha Verma
Your city: Kochi
Your age: 21
Hello Isha Verma from Kochi!
In 5 years you will be 26.

The prompts use print, not println, so the cursor waits on the same line. Notice the brackets in (age + 5): without them, Java would join "...will be " + age as text first and print 215.

The nextInt and nextLine trap

Almost every Java student meets this bug. When the user types 27 and presses Enter, the input contains 27 followed by an invisible line break. nextInt() reads 27 but leaves the line break behind. The next nextLine() sees that leftover line break immediately and returns an empty string, without waiting for the user.

Java
import java.util.Scanner;

public class Trap {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);

        System.out.print("Roll number: ");
        int roll = in.nextInt();

        System.out.print("Full name: ");
        String name = in.nextLine();      // reads the leftover Enter!

        System.out.println("Roll " + roll + ", name [" + name + "]");
    }
}
Output
Roll number: 27
Full name: Roll 27, name []

The program never waited for the name. There are two common fixes. You can call in.nextLine(); once after nextInt() to throw away the rest of the line. Or, more robustly, read every input as a full line and convert it yourself:

Java
import java.util.Scanner;

public class Fixed {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);

        System.out.print("Roll number: ");
        int roll = Integer.parseInt(in.nextLine().strip());

        System.out.print("Full name: ");
        String name = in.nextLine();

        System.out.println("Roll " + roll + ", name [" + name + "]");
    }
}
Output
Roll number: 27
Full name: Rohan Gupta
Roll 27, name [Rohan Gupta]

Checking that the input is a number

If the user types twenty when nextInt() expects a number, the program crashes with java.util.InputMismatchException. Before reading, you can ask the scanner what is coming next with hasNextInt() or hasNextDouble(). The program below keeps asking until it gets a whole number. It uses a while loop, which you will learn properly in Loops: the code inside repeats while the condition is true.

Java
import java.util.Scanner;

public class Bill {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);

        System.out.print("How many plates of pani puri? ");
        while (!in.hasNextInt()) {
            String wrong = in.next();
            System.out.print("'" + wrong + "' is not a number. Try again: ");
        }
        int plates = in.nextInt();

        System.out.print("Price per plate: ");
        double price = in.nextDouble();

        System.out.printf("Pay Rs %.2f%n", plates * price);
    }
}
Output
How many plates of pani puri? two
'two' is not a number. Try again: 2
Price per plate: 35
Pay Rs 70.00

in.next() removes the bad word from the input; without it, hasNextInt() would look at the same word forever. In Exceptions you will learn the other approach: try to parse, and catch the error if it fails.

The Java 25 way: IO.readln

Command-line arguments

There is a second way to give a program input: type values after the program name when you start it. They arrive in the String[] args parameter of main. args.length tells you how many there are, and args[0] is the first one. Wrap a value in quotes if it contains a space.

Java
public class Greet {
    public static void main(String[] args) {
        System.out.println("Arguments received: " + args.length);
        if (args.length > 0) {
            System.out.println("Hello, " + args[0] + "!");
        }
    }
}
Terminal
java Greet.java "Meera Nair" Pune
Output
Arguments received: 2
Hello, Meera Nair!

Command-line arguments are how real tools receive options: javac Hello.java passes Hello.java as an argument to the compiler.

Common mistakes

  • Forgetting the import. In a normal class, Scanner needs import java.util.Scanner;, or you get error: cannot find symbol. (Java 25 compact source files import it automatically.)
  • Mixing nextInt() and nextLine(). Remember the leftover line break, or read every line with nextLine() and parse it.
  • Not handling bad input. nextInt() throws InputMismatchException on text. Check with hasNextInt() first.
  • Reading args[0] when no arguments were given. That throws ArrayIndexOutOfBoundsException. Check args.length first.

Key points

  • Create one Scanner in = new Scanner(System.in); and reuse it.
  • nextLine() reads a whole line; next(), nextInt() and nextDouble() read one token.
  • After nextInt(), the line break stays in the input; read lines and parse them to avoid surprises.
  • Use hasNextInt() to check input before reading it.
  • Java 25 adds IO.readln(prompt), which returns a whole line as a String.
  • Command-line arguments arrive in String[] args.

Exercise

Write Electricity.java that asks for the customer name and the units used this month (read both with nextLine and convert the units with Integer.parseInt). Charge Rs 5 per unit for the first 100 units and Rs 7 per unit after that (use Math.min and Math.max so you do not need an if yet). Print the bill with two decimal places.

Show solution
Java
import java.util.Scanner;

public class Electricity {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);

        System.out.print("Customer name: ");
        String name = in.nextLine();
        System.out.print("Units used: ");
        int units = Integer.parseInt(in.nextLine().strip());

        int firstSlab = Math.min(units, 100);
        int secondSlab = Math.max(units - 100, 0);
        double amount = firstSlab * 5.0 + secondSlab * 7.0;

        System.out.printf("%s, your bill for %d units is Rs %.2f%n", name, units, amount);
    }
}
Output
Customer name: Priya Sharma
Units used: 160
Priya Sharma, your bill for 160 units is Rs 920.00

The first 100 units cost Rs 500 and the remaining 60 cost Rs 420. Math.max(units - 100, 0) makes sure the second slab is never negative for small bills.

Quick Quiz

1. Which method reads a full line of text, including spaces?

2. After int n = in.nextInt(); the next in.nextLine() returns an empty string. Why?

3. What type does Java 25's IO.readln("Age: ") return?

4. You run java Greet.java Aarav Jaipur. What is args[1]?

Learn Java with a mentor

Free lessons get you started. Our Java, C & C++ Programming training adds real projects and code reviews from working developers.

  • Project-based learning
  • Mentor code reviews
  • Free counselling call