Validate input data
Validate data
Prevent exceptions from being thrown
How to prevent exceptions from being thrown
- The has methods of the Scanner class let you check whether additional data is available at the console and whether that data can be converted to a specific data type.
- You can use the Scanner has methods to prevent an exception from being thrown when one of the next methods is called.
- You can use the nextLine method to retrieve and discard any additional data that the user enters on a line that isn't required.
Methods of the Scanner class you can use to validate data
Method | Description |
---|---|
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. |
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 }
import java.util.Scanner;
import java.util.InputMismatchException;
public class InvoiceApp
{
public static void main(String[] args)
{
// welcome the user to the program
System.out.println("Welcome to the Invoice Total Calculator");
System.out.println(); // print a blank line
// create a Scanner object named sc
Scanner sc = new Scanner(System.in);
// perform invoice calculations until choice isn't equal to "y" or "Y"
String choice = "y";
while (choice.equalsIgnoreCase("y"))
{
// get the invoice subtotal from the user
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
}
// calculate the discount amount and total
double discountPercent= 0.0;
if (subtotal >= 200)
discountPercent = .2;
else if (subtotal >= 100)
discountPercent = .1;
else
discountPercent = 0.0;
double discountAmount = subtotal * discountPercent;
double total = subtotal - discountAmount;
// display the discount amount and total
String message = "Discount percent: " + discountPercent + "\n"
+ "Discount amount: " + discountAmount + "\n"
+ "Invoice total: " + total + "\n";
System.out.println(message);
// see if the user wants to continue
System.out.print("Continue? (y/n): ");
choice = sc.next();
System.out.println();
}
}
}
Code that prevents a NullPointerException
if (customerType != null) { if (customerType.equals("R")) discountPercent = .4; }