Way2Java

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();
  }
}

Output 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.

Java Scanner Checking Tokens

Reading a file with Scanner

Following is the third program on Scanner (first one being reading from keyboard) that reads from a file with default delimiter and user-defined delimiter.

import java.util.Scanner;
import java.io.FileNotFoundException;
import java.io.File;

public class FileReadingWithScanner
{
  public static void main(String args[]) throws FileNotFoundException
  {
    File f1 = new File("RKMutt.txt");
    Scanner scan = new Scanner(f1);
		// using whitespace as delimiter which is default
    System.out.println("\tReading and printing each word:");
    while(scan.hasNext())
    {
      String s1 = scan.next();
      System.out.println(s1);
    }
    scan.close();
				// to use our own delimiter
    Scanner scan1 = new Scanner(f1);
    scan1.useDelimiter(System.getProperty("line.separator")); 
    
    System.out.println("\tReading and printing each line (not each word):");
    while(scan1.hasNext()) 
    {
      String str = scan1.next();    
      System.out.println(str);
    }
    scan1.close();
  }
}


Output screenshot on Java Scanner Checking Tokens

File f1 = new File("RKMutt.txt");
Scanner scan = new Scanner(f1);

A File object, f1 representing the text file RKMutt.txt is passed as parameter to the Scanner constructor. The scan object checks each word in the file taking whitespace as delimiter.

Scanner scan1 = new Scanner(f1);
scan1.useDelimiter(System.getProperty("line.separator"));

The scan1 object treats line seprator (obtained by typing entering key in the source file) as the delimiter. For this reason, the hasNext() method in the second while loop treats the whole line as a single word and next() method reads the whole line (and not each word as in the earlier while loop).