Code that gets a valid double value within a specified range
*******************************************************
Scanner sc = new Scanner(System.in);
double subtotal = 0.0;
boolean isValid = false;
while (isValid == false)
{
// get a valid double value
System.out.print("Enter subtotal: ");
if (sc.hasNextDouble())
{
subtotal = sc.nextDouble();
isValid = true;
}
else
{
System.out.println("Error! Invalid number. Try again.\n");
}
sc.nextLine(); discard any other data entered on the line
// check the range of the double value
if (isValid == true && subtotal <= 0)
{
System.out.println("Error! Number must be greater than 0.");
isValid = false;
}
else if (isValid == true && subtotal >= 10000)
{
System.out.println("Error! Number must be less than 10000.");
isValid = false;
}
}
*******************************************************
Note:
1. A user enter data, to make sure a data validation.
2. When an entry is invalid, display an error, give a
chance to enter again by using a while loop.
3. Two types of checking a numberic entry are
1. to make sure that a valid numberic format
2. to make sure that a valid range (range checking)