即使满足条件,循环也会继续循环

时间:2019-07-01 11:07:15

标签: java while-loop

我正在编写一个计算斐波那契数并将其写入文本文件的程序。我已经编写了所有代码,除了一点点以外,它的工作方式应该如何。 我正在尝试在程序启动之前与用户输入进行while循环,以使用户确认何时启动。

但是,每当我运行它时,即使满足条件,while循环仍会不断要求用户输入。然后我对其进行了更改以尝试对其进行修复,但是当我运行它时,即使条件不正确,它的行为也似乎满足了条件。

System.out.println("Enter [y] to run the program: ");
String run = input.nextLine();
while (run.toLowerCase() != "y") {
    System.out.println("Enter [y] to run the program: ");
    run = input.nextLine();
}

我希望输入单个字母y会结束while循环,但是由于某些原因它不起作用,即使输入了y,它也会不断重复。

以下是输出:

Enter [y] to begin the program:
y
Enter [y] to begin the program:
y
Enter [y] to begin the program:
y

该如何解决?

0 个答案:

没有答案