Lesson 39 +10 XP

Java User Input

Java User Input

Use the Scanner class to read input typed by the user. It lives in the java.util package.

Create a Scanner

import java.util.Scanner;

Scanner myObj = new Scanner(System.in);

System.in is the keyboard input stream.

Read different types

MethodReads
nextLine()a whole line of text
next()a single word
nextInt()an integer
nextDouble()a decimal number
nextBoolean()true or false

Example: read a line

import java.util.Scanner;

class Main {
  public static void main(String[] args) {
    Scanner myObj = new Scanner(System.in);
    System.out.println("Enter username");

    String userName = myObj.nextLine();
    System.out.println("Username is: " + userName);
  }
}

Close the scanner

When you are done, close it to free resources:

myObj.close();

TL;DR

  • Import java.util.Scanner and create new Scanner(System.in).
  • nextLine(), nextInt(), nextDouble() read typed values.
  • Close the scanner when finished.