java - while 循环没有完成

标签 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");
}

很抱歉问了这么个愚蠢的问题,但我真的被困在这个问题上了,我点击了“n”,但 while 循环并没有停止,而是继续工作。我做错了什么吗?当用户输入“n”表示否时,我应该如何完成循环?

最佳答案

一个问题是:

sc.next() == "n"

应该是

sc.next().equals("n")

String 比较应该使用 equals() 而不是 ==(字符串文字比较除外)并且最好遵循 java code conventions .

关于java - while 循环没有完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14073750/

相关文章:

java - Morphia Complex Mongodb 聚合($substr、$project、$sort 等...)

java - 尝试使用 maven 安装项目时出现 NoClassDefFoundError

java - 插件开发: create new file dialog using FileDialog

c++ - 没有计数器的for循环的可读性

C++ - 使用 cin 运行 while 循环后,程序将不再接受输入

java - Java 中对象的命名约定

java - 交换 Activity 后如何保持 countDownTimer 计数?

java - HttpClient 忽略编码,在一台计算机上

java - 如何在eclipse中创建一个文件夹来存储序列化对象?

scala - 是否可以根据 Chisel 数据类型的条件在 Chisel 中进行 while 循环?