为什么我的java代码会进入无限循环?

时间:2016-07-24 01:49:06

标签: java loops

我的代码似乎陷入了无限循环,我对此感到困惑。我介绍了一些代码,直到我触发了错误消息:

import java.util.Scanner;

public class Average
{
    public static void main(String[] args)
    {
        Scanner in = new Scanner(System.in);
        int count = 0;
        double sum = 0;
        System.out.print("Enter a value: ");
        boolean notDone = true;
        while (notDone)//go into loop automatically
        {
            if(!in.hasNextDouble()){
                if(count==0){//this part generates bugs
                    System.out.print("Error: No input");
                }else{
                    notDone = false;
                }

            }else{
                sum+= in.nextDouble();
                count++;
                System.out.print("Enter a value, Q to quit: ");
            }
        }
        double average = sum / count;
        System.out.printf("Average: %.2f\n", average);
        return;
    }
}

正如评论中所指出的,罪魁祸首是这些界限:

                if(count==0){ //this part generates bugs
                    System.out.print("Error: No input");
                }

这个if情况的目的是让用户留在循环中并被提醒需要有效输入,直到它收到有效输入,但它不像没有办法爆发循环,因为用户可以在程序收到有效输入(至少一个double值,后跟非double值)的条件下中断循环。

干杯。

1 个答案:

答案 0 :(得分:2)

您的代码进入无限循环,因为如果未检测到double,条件不会取得任何进展。发生这种情况时,您会打印一条消息,但不会从扫描仪中删除垃圾输入。

in.nextLine()添加到条件将解决此问题:

if(!in.hasNextDouble()){
    if (!in.hasNextLine()) {
        // The input is closed - exit the program.
        System.out.print("Input is closed. Exiting.");
        return;
    }
    in.nextLine();
    ... // The rest of your code
} ...
相关问题