Mah*_*ari 1 java eclipse while-loop
我是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");
}
Run Code Online (Sandbox Code Playgroud)
很抱歉问这么愚蠢的问题,但我真的陷入了这个问题,我点击了"n",但是while循环没有停止,并继续工作.我做错了什么吗?当用户输入"n"表示否时,我该怎么做才能完成循环?
kos*_*osa 10
一个问题是:
sc.next() == "n"
Run Code Online (Sandbox Code Playgroud)
应该
sc.next().equals("n")
Run Code Online (Sandbox Code Playgroud)
String比较应该使用equals()而不是==(字符串文字比较除外),并且遵循Java代码约定总是更好.