<<< Scanner input validation | Index | Code that prevents a NullPointerException >>> |
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 }
Console output:
Enter subtotal: $100 Error! Invalid number. Try again. Enter subtotal:
<<< Scanner input validation | Index | Code that prevents a NullPointerException >>> |