Java User Input

TheNewBoston Video – User Input

Learn Java the Hard Way – Getting Input From a Human

Here’s an example program that asks the user a question and stores the answer as a String variable:

import java.util.Scanner;

class quiz {
    public static void main(){
	System.out.println("Say something: ");
	Scanner scan = new Scanner(System.in);
	String answer = scan.nextLine();
	System.out.println("You said " + answer);
    }	
}

We are creating a Scanner object to read user input.

Notice the import statement before the class. Java needs this, or it won’t be able to make a Scanner.

One of the lines creates a new Scanner object called scan (this could be some other name of your choice).

The following line with “scan.nextLine()” retrieves the first line of the user’s response and saves it into the String variable answer.

Now this user response data is stored in  memory and can be used by your program.

You don’t have to create the scanner repeatedly. You can do “new Scanner(System.io)” line once and then repeatedly use the Scanner’s nextLine() method to get additional input from the user.

Getting Numbers:

The values from nextLine() are always String type. If you want int data instead, you can use the scanner’s nextInt() method instead.

NextInt example from TutorialsPoint

(This tutorial also shows how to account for the possibility that the input doesn’t contain an int value)