/** * ========================================================================== * Scanner2.java: The class Scanner provides support for parsing of primitive * data types (e.g., int, float and double) and strings. A Scanner breaks its * input into tokens, which by default will be delimited by whitespace. The * tokens may then be converted into values of different types using the * various next methods. * * This program demonstrates use of a Scanner for input of text, integers, * and floating-point numbers from the keyboard (i.e., System.in). However, * unlike Scanner1.java, this version includes support for repeating a * prompt until the correct type of data is supplied. * * Written by: Mark Austin June 2009 * ========================================================================== */ import java.util.Scanner; import java.util.InputMismatchException; public class Scanner2 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); // Prompt the user for his/her first name. System.out.print("Please enter your FIRST name (only): "); String name = sc.next(); // Repeat prompting until an integer age is supplied .... int age = 0; while (age == 0) { System.out.print("Please enter your age as an integer: "); if (sc.hasNextInt() == true) age = sc.nextInt(); else System.out.println("Error: " + sc.next() + " isn't a proper integer ..."); } // Repeat prompting until a double-precision temperature is supplied .... double temperature = 0.0; while (temperature == 0.0) { System.out.print("Please enter your current body temperature (degrees F): "); if (sc.hasNextDouble() == true ) temperature = sc.nextDouble(); else System.out.println("Error: " + sc.next() + " isn't a proper double ..."); } System.out.println(name + " is " + age + " years old."); System.out.println(name + "'s temparature is " + temperature + " degrees F."); } }