简体   繁体   中英

Why is else statement a infinite loop?

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.");
    }

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

要解决此问题,请在您的else分支中添加一个scan.nextLine()

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM