<<< Scanner hasNextDouble example | Index | The Catch or Specify Requirement >>> |
A method that gets a valid numeric format
public static double getDouble(Scanner sc, String prompt) { double dbl = 0.0; boolean isValid = false; while (isValid == false) { System.out.print(prompt); if (sc.hasNextDouble()) { dbl = sc.nextDouble(); isValid = true; } else { System.out.println( "Error! Invalid number. Try again."); } sc.nextLine(); // discard any other data } return dbl; }
<<< Scanner hasNextDouble example | Index | The Catch or Specify Requirement >>> |