One of the features of Java is "robust". It does not allow the programmer, to the maximum extent, to commit mistakes. For example, giving the size of the array in array initialization is a compilation error. Java designers included many methods in Scanner class intended to check the input whether it is a byte, short, long and double etc. For example, reading with nextInt() when user enters a double is an exception like InputMismatchException. So the programmer should take every care to see what the user entered and accordingly use appropriate nextXXX() method to read.
The checking methods are of type hasNextXXX() like hasNext(), hasNextBoolean(), hasNextShort(), hasNextInt() and hasNextDouble() etc. that checkes the input is a word, a boolean, a short, an integer or a double.
The earlier KeyboardReading3.java is modified to check the input with the above methods.
public class CheckingKeyboardInput
public static void main(String args)
Scanner scanf = new Scanner(System.in);
System.out.println("Please enter some value you like: ");
int x = scanf.nextInt();
System.out.println("You entered: " + x);
double y = scanf.nextDouble();
System.out.println("You entered: " + y);
boolean b = scanf.nextBoolean();
System.out.println("You entered: " + b);
System.out.println("What you entered I assume as a word.\nYou entered: " + scanf.next());
The methods used in the above program are hasNextInt(), hasNextDouble(), hasNextBoolean() and hasNext(). After checking the input whether it is an integer, a double value, a boolean and still not, the input is checked with hasNext() which evaluates to true in all the cases as it treats every input as word. Using hasNext() at the end is the safe programming as it avoids InputMismatchException.