๐ŸŽ“ A1Learner
๐Ÿ”

Java User Input

User input is data that a program reads from the keyboard while it runs. The Scanner class reads that data as lines, whole numbers, and decimals.

Read one line of text

The prompt prints first. The nextLine call then reads the typed name.

import java.util.Scanner;
public class Main {
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.println("Enter your name:");
    String name = scanner.nextLine();
    System.out.println("Hello, " + name);
  }
}

Read a line, then a number

The line is read first. The whole number is read second.

import java.util.Scanner;
public class Main {
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.println("Enter your name:");
    String name = scanner.nextLine();
    System.out.println("Enter your age:");
    int age = scanner.nextInt();
    System.out.println(name + " is " + age + " years old");
  }
}

Read two whole numbers

Each nextInt call reads one whole number. The program adds the two numbers and prints the sum.

import java.util.Scanner;
public class Main {
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.println("Enter the first number:");
    int first = scanner.nextInt();
    System.out.println("Enter the second number:");
    int second = scanner.nextInt();
    System.out.println(first + second);
  }
}

Example

import java.util.Scanner;
public class Main {
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.println("Enter the item:");
    String item = scanner.nextLine();
    System.out.println("Enter the price:");
    double price = scanner.nextDouble();
    System.out.println("Enter the quantity:");
    int quantity = scanner.nextInt();
    double total = price * quantity;
    System.out.println(item + " total: " + total);
  }
}

Key points

  • The Scanner class reads input from the keyboard through System.in.
  • A Scanner object is created with new Scanner(System.in).
  • The nextLine method reads one whole line of text.
  • The nextInt method reads a whole number, and nextDouble reads a decimal number.
  • A prompt printed with println before a read names the value to type.

In this example, the program reads a line, a decimal, and a whole number in that order. The item is Notebook, the price is 12.5, and the quantity is 3. The total line multiplies the price by the quantity. The last line prints the item with a total of 37.5.

Note

A nextLine call after nextInt can read the leftover end of the number line, so this lesson reads lines before numbers.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Programiz Java Compiler

Exercise

Which Scanner method reads one whole line of text?