Starting in Java 5, a built in class to take input was incorporated. This class is called the Scanner class and takes care of the back end intricacies of input and creates a simple way to get console information from a user. To use the Scanner class you must create a Scanner variable. Scanner variables are reference type variables, so they need to be declared and instantitated. When instantiating a Scanner variable, System.in must be passed as a parameter so that the Scanner knows to read from the keyboard. Also, there is an import required in order to use the Scanner class. So, programs that need to take user input will begin as follows:
import java.util.Scanner;
public class Input{
public static void main(String [] args){
Scanner reader=new Scanner(System.in);
...remainder of program follows
In line (1) the Scanner class, part of the Java library, is imported into the program. In line (4), a Scanner object is instantiated. This only has to be done ONCE a program. All input can use this instance.
The variable reader in the program above can be named anything the programmer desires, as long as they follow the Java language rules for naming identifiers. Other options that are often used are input, io, read, etc. The following methods are part of the Scanner class:
nextInt(); //returns an int
nextDouble(); //returns a double
nextBoolean(); //returns a boolean
nextLine(); //returns a String, terminated by a newline
next(); //returns a String, terminated by whitespace
At a basic level, Scanner input would look like this:
System.out.println("Enter your age:");
int age=reader.nextInt(); //use next Int because the age variable is an int
System.out.println("You are "+age+" years old.");
Since there is no method to read a character variable, we have to read a string and find the character at its first spot.
System.out.println("What is your first initial?");
char initial=reader.nextLine().charAt(0);
Scanner Class Input Issue
There is a special case that can cause input errors with the Scanner class. This is caused by how the object reads from the stream. When an integer or double is read, the Scanner object reads the next number until it encounters whitespace (space, tab, return, etc). If we are reading multiple number consecutively, no problem. But, if we read a number followed by a string - big problem. What happens is the program will read the number and leave the users return on the stream. So, when it goes to read the nextLine(), it first finds the return character and stores nothing in the String variable.
This can be fixed with a dummy read - a call to read input that is not stored in a variable.
System.out.println("Enter your age:");
int age=reader.nextInt();
reader.nextLine(); //dummy read to take the return off the stream
System.out.println("Enter your name:");
String name=reader.nextLine();
Note: This practice is only necessary when you are going to take a String AFTER you have read an integer or double.