<<< Code that prevents a NullPointerException | Index | Another Scanner hasNextDouble example >>> |
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."); } 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; } }
<<< Code that prevents a NullPointerException | Index | Another Scanner hasNextDouble example >>> |