1

I am fairly new to Java and I am trying to work on my data validation. The code runs fine when I use valid data, but when I put in a string instead of an integer the code just loops forever. It just loops the, "Bad input. Please enter a number." Thanks in advance!

    //Get input from user
    System.out.print("What is your name (Last, First)? ");
    String name = scan.nextLine();
    System.out.print("enter a date:");
    String datein = scan.nextLine();

    boolean valid = false;
    while (valid != true)
    {   
        System.out.print("Electricity used (KW):");
        if (scan.hasNextDouble())
        {
            electricityUsed = scan.nextDouble();
            valid = true;
        }
        else
            System.out.println("Bad input. Please enter a number.");
    }

3 Answers3

8

because hasNextDouble always returns false.

here is the doc. You answer your own question :

but when I put in a string instead of an integer

NimChimpsky
  • 46,453
  • 60
  • 198
  • 311
  • 2
    +1 If you type anything but a double, it will keep finding that it is not a double, and never consume it. Add `scan.nextLine();` to the `else` block. – Peter Lawrey Dec 31 '12 at 10:47
  • Thank you very much guys. the scan.nextLine(); fixed the problem. Thank you for the link above about hasNextDouble. – user1939469 Dec 31 '12 at 23:55
3

To fix it add a scan.nextLine() to your else branch.

Henry
  • 42,982
  • 7
  • 68
  • 84
2

A simpler approach is to use the following.

System.out.print("Electricity used (KW):");
while(!scan.hasNextDouble()) {
    scan.nextLine();
    System.out.println("Bad input. Please enter a number.");
    System.out.print("Electricity used (KW):");
}
double electricityUsed = scan.nextDouble();
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130