import java.util.InputMismatchException; import java.util.Scanner; /** * Class reads values from the console. */ public final class Console { private Console() {}; // Cannot create objects of this class. /** Scanner object connected to System.in. */ private static Scanner keyboard = new Scanner(System.in); /** * Reads an int value from the keyboard. * @return Next value as int */ public static int readInt() { while (true) try { return keyboard.nextInt(); } catch (InputMismatchException ime) { reportError(); } } /** * Reads a double value from the keyboard. * @return Next value as double */ public static double readDouble() { while (true) try { return keyboard.nextDouble(); } catch (InputMismatchException ime) { reportError(); } } /** * Reads a string from the keyboard. * The returned string will not contain any white space. * @return Next value as string. */ public static String readString() { while (true) try { return keyboard.next(); } catch (InputMismatchException ime) { reportError(); } } /** * Reads to the end of line (EOL). * @return Remaining input as string. */ public static String readToEOL() { while (true) try { return keyboard.nextLine(); } catch (InputMismatchException ime) { reportError(); } } /** * Empties the current line, and prints an error message * to the terminal window. */ private static void reportError() { keyboard.nextLine(); // Empty the line first. System.out.println("Error in input. Try again!"); } }