Scanner (J2SE 5.0)
The Scanner class, defined in the java.util package, has been introduced to facilitate reading input from the console window in Java programs. (Core Java, p. 58). First create an instance of Scanner that connects to the standard input stream.
Scanner in = new Scanner(System.in);
Now use various methods of the Scanner class to read input, as shown here:
System.out.println("What is your name?");
String name = in.nextLine();
The nextLine method reads in a line of input. To read a single word, use the next method:
String name = in.next();
To read an integer, use the nextInt method:
int age = in.nextInt();
Here's a complete example utilizing Scanner functionality:
import java.util.*;
public class InputTest
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
System.out.print("What is your name? ");
String name = in.nextLine();
System.out.print("How old are you? ");
int age = in.nextInt();
System.out.println("Hello, " + name + ". Next year, you'll be " + (age + 10));
}
}
Next... page 7-19a