Tsallaka zuwa abun ciki
Justice Tech School

User Input with Scanner

The Scanner class reads typed input: nextLine for a whole line, nextInt for an integer and nextDouble for a decimal. Remember to import java.util.Scanner. Interactive input cannot run on this page, so the example is shown with a sample session.

Example
import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    System.out.print("Name: ");
    String name = in.nextLine();
    System.out.print("Age: ");
    int age = in.nextInt();
    System.out.println(name + " will be " + (age + 1) + " next year");
  }
}

// sample run:
// Name: Ada
// Age: 30
// Ada will be 31 next year

Exercise

Read a whole line.

String s = in.();

Quiz Test

Which package holds Scanner?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.