The class Scanner allows you easily to associate a variable with one of a number of different input streams such as the keyboard, a file or a string:
0047: Scanner tScannerKeyboard = new Scanner(System.in); 0048: Scanner tScannerInputFile = new Scanner(new File("input.txt")); 0049: Scanner tScannerSomeString = new Scanner(tSomeString);
You can then apply methods such as nextInt to read a value from the input stream. Here, an unchecked exception java.util.InputMisMatchException will be thrown if the next token is not an int.
To avoid the possibility of this exception occurring, a method like hasNextInt can be used to determine if the next value is an int, as shown in this program:
0067: import java.util.Scanner; // Analyse.java 0068: public class Analyse 0069: { 0070: public static void main(String[] pArgs) 0071: { 0072: Scanner tScanner = new Scanner(System.in); 0073: System.out.print("Type in a value: "); 0074: if (tScanner.hasNextInt()) { 0075: int tFirst = tScanner.nextInt(); 0076: System.out.println("Got an int: " + tFirst); 0077: } 0078: else if (tScanner.hasNextDouble()) { 0079: double tFirst = tScanner.nextDouble(); 0080: System.out.println("Got a double: " + tFirst); 0081: } 0082: else { 0083: String tFirst = tScanner.nextLine(); 0084: System.out.println("Got a string: " + tFirst); 0085: } 0086: } 0087: }