Methods of the Scanner class you can use to validate data
*******************************************************

hasNext()       Returns true if the scanner contains another token.

hasNextInt()    Returns true if the scanner contains another token that can be converted to an int value.

hasNextDouble() Returns true if the scanner contains another token that can be converted to a double value.

nextLine()      Returns any remaining input on the current line as a String object and advances the scanner to the next line.

******************************************************* 
example 1. Code that prevents an InputMismatchException

double subtotal = 0.0;
System.out.print("Enter subtotal:  ");
if (sc.hasNextDouble())

     subtotal = sc.nextDouble();

else
{
     sc.nextLine();  // discard the entire line
     System.out.println("Error! Invalid number. Try again.\n");
     continue;       // jump to the top of the loop
}


*******************************************************

example 2: Code that prevents a NullPointerException


if (customerType != null)
{

    if (customerType.equals("R"))
        discountPercent = .4;  

}


*******************************************************


Description:

1. The has methods of the Scanner class let you check
   whether additonal data is available at the console
   and whether that data can be converted to a specific
   data type. You can use these methods to prevent an
   exception from being thrown when one of the next
   methods is called.
2. You can use the nextLine method to retrieve and 
   discard any additional data that the user enters
   on a line that isn't required by the application.
3. When hour code prevents an exception from being
   thrown, it runs faster that code that catches and
   then handles the exception.


*******************************************************
Site hosted by Angelfire.com: Build your free website today!