我是 Java 的新手,我已经开始使用一些简单的控制台应用程序。
这是我当前应用程序的代码:
Scanner sc = new Scanner(System.in);
boolean ExitLoop = false;
ArrayList<Integer> IDs = new ArrayList<Integer>();
ArrayList<Double> averages = new ArrayList<Double>();
while(!ExitLoop)
{
System.out.println("StudentID: ");
IDs.add(sc.nextInt());
System.out.println("Average: ");
averages.add(sc.nextDouble());
System.out.println("Do you want to register another student? [y/n] ");
ExitLoop = (sc.next() == "n");
}
很抱歉问了这么个愚蠢的问题,但我真的被困在这个问题上了,我点击了“n”,但 while 循环并没有停止,而是继续工作。我做错了什么吗?当用户输入“n”表示否时,我应该如何完成循环?
最佳答案
一个问题是:
sc.next() == "n"
应该是
sc.next().equals("n")
String
比较应该使用 equals()
而不是 ==(字符串文字比较除外)并且最好遵循 java code conventions .
关于java - while 循环没有完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14073750/