Java Scanner Checking Tokens

Java Scanner Checking Tokens

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 is modified to check the input with the above methods.

Java Scanner Checking TokensOutput screen on Java Scanner Checking Tokens

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.

Leave a Reply

Your email address will not be published. Required fields are marked *