A method that gets a valid numberic format
*******************************************************
public static double getDouble(Scanner sc, String prompt)
{
      double d = 0.0;
      boolean isValid = false;
      while (isValid == false)
      {
             System.out.print(prompt);
             if (sc.hasNextDouble())
             {
                 d = sc.nextDouble();
                 isValid = true;
             }
             else
             {
                 System.out.println("Error! Invalid number. Try again");

             }
             sc.nextLine()     // discard any other data entered on the line    
      }
      return d;

}

*******************************************************
A method that checks for a valid numeric range
*******************************************************

public static double getDoubleWithinRange(Scanner sc, String prompt, double min, double max)
{
      double d = 0.0;
      boolean isValid = false;
      while (isValid == false)
      {
             d = getDouble(sc, prompt);  // call the getDouble method
             if (d <= min)
             {
                   System.out.println("Error! Number must be greater than" + min + ".");

             }
             else if (d >= max)
             {
                   System.out.println("Error! Number must be less than " + max ".");

             }
             else
                 isValid = true;
      }
      return d;
}

*******************************************************
Code that uses these methods to return two valid double values
*******************************************************


Scanner sc = new Scanner(System.in);
double subtotal1 = getDouble(sc, "Enter subtotal: ");
double subtotal2 = getDoubleWithinRange(sc, "Enter subtotal: ", 0, 10000);



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

Note:***

Because most applications need to check more than 
one type of entry for validity , it often make sense to create and use generic methods for data validation.



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