使用sc.hasNextLine()进行无限循环

时间:2020-03-07 19:55:45

标签: java loops input output infinite-loop

我正在尝试使用输入,但是我遇到了麻烦……如果我使用下面的代码,它还没有结束……所以我陷入了无限循环。即使我输入的文件结尾,它也会这样写:

...
A number has not been parsed from line n
A number has not been parsed from line n+1
A number has not been parsed from line n+2
... (infinite)

但是我想代替这个:

...
End of input detected!

输入看起来像这样:

1
2
3
4
5
double[] numbers = new double[10];
int counter_number = 0;
while (sc.hasNextLine()) {
        ...
        line++;
        if(sc.hasNextDouble()) {
            numbers[counter_number] = sc.nextDouble();
            counter_number++;
        }
        else{
            System.out.println("A number has not been parsed from line "+ line);
            continue;
        }
        if (sc.hasNextLine() == false) {
            System.err.println("End of input detected!");
        }
        if (((counter_number)==10) || ((sc.hasNextLine() == false) 
                ...
            counter_number = 0;
        }
    }

这个循环永远不会结束吗?我看到了他们在其中使用“ while(sc.hasNextLine())”的教程,并且教程完成了。我是Java的初学者。

2 个答案:

答案 0 :(得分:0)

您执行的唯一执行读取器的操作是sc.nextDouble(),但这仅在sc.hasNextDouble()返回true的情况下发生。这意味着如果您的代码遇到非双输入,它将永远被卡住

作为一般说明-sc.hasNextLine() == false应替换为!sc.hasNextLine()

答案 1 :(得分:0)

static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
    double[] numbers = new double[10];
    int counter_number = 0;
    int line = 0;

    while (sc.hasNextLine()){

        line++;

        String thisLine = sc.nextLine();
        // this is what i wrote.

        if(thisLine.trim().isEmpty()) {
            // if the line is empty, will exit the loop.

            System.out.println("lines: "+line); // lines
            System.out.println("End of input detected!"); // end.
            break;
        }

        try {
            // if the input is a double
            numbers[counter_number] = Double.parseDouble(thisLine);
            counter_number++;

        } catch (NumberFormatException e) {
            // if not
            System.out.println("A number has not been parsed from line "+ line);
            continue;
        }

        // idk
        if (counter_number == numbers.length) {
            counter_number = 0;
        }
    };

}

FIX。我不会关闭扫描仪,并且...您可以尝试使用此功能。当我输入空行时,此代码结束。