// Test some of the Scanner import java.util.Scanner; public class TestScanner { public static void main(String[ ] argv) { String name = "", gender = "", line = "", word = ""; int age = 0; double gpa = 0.0; // Create a Scanner object from System.in. // System.in conforms to the Readable interface. Scanner s = new Scanner(System.in); // Enter these two lines at the keyboard: // Alice F 23 3.95 // This is a test. System.out.println("Enter the two input lines:"); // Read name. if (s.hasNext( )) name = s.next( ); else return; // Read gender. if (s.hasNext( )) gender = s.next( ); else return; // Read age. if (s.hasNextInt( )) age = s.nextInt( ); else return; // Read gpa. if (s.hasNextDouble( )) gpa = s.nextDouble( ); else return; // Read line. if (s.hasNextLine( )) line = s.nextLine( ); else return; System.out.printf("name == %s\n", name); System.out.printf("gender == %s\n", gender); System.out.printf("age == %d\n", age); System.out.printf("gpa == %f\n", gpa); System.out.printf("line == %s\n", line); // Test scanner methods for Scanner object // created from a delimited string. Scanner t = new Scanner("this is a test"); while (t.hasNext( )) { word = t.next( ); System.out.println("\"" + word + "\""); } } } // Keyboard input and screen: Enter the input line: Alice F 23 3.95 This is the rest of the line. name == Alice gender == F age == 23 gpa == 3.45 line == This is the rest of the line. "this" "is" "a" "test"