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

import java.util.Scanner;
public class CheckingKeyboardInput
{
  public static void main(String[] args)
  {
    Scanner scanf = new Scanner(System.in);
    System.out.println("Please enter some value you like: ");
   
    if(scanf.hasNextInt())
    {
      int x = scanf.nextInt();
      System.out.println("You entered: " + x);
    }
    else if(scanf.hasNextDouble())
    {
      double y  = scanf.nextDouble();
      System.out.println("You entered: " + y);
    }
    else if(scanf.hasNextBoolean())
    {
      boolean b = scanf.nextBoolean();
      System.out.println("You entered: " + b);
    }             
    else if(scanf.hasNext())
    {
      System.out.println("What you entered I assume as a word.\nYou entered: " + scanf.next());
    }
    scanf.close();
  }
}

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 Comment

Your email address will not be published.