Java:while循环未检测到中断条件,但如果块检测到
只是想打破这个while循环。当我假设条件会中断时,它不会中断,但它确实会被后续的if语句注册
String current_Class_Name = "";
int current_Class_Rating;
while(!current_Class_Name.equals("Done")) {
// * Get class name.
System.out.println("What class are you rating?");
current_Class_Name = in.nextLine();
// *
// if(current_Class_Name.equals("Done")) {
// System.out.println("Detected 'Done'");
// break;
// }
// * Get class rating.
System.out.println("How many plus signs does " + current_Class_Name + " get?");
current_Class_Rating = Integer.parseInt(in.nextLine());
// * If user inputs an invalid rating (not a value between 0-5),
// * keep prompting them until they enter a valid input.
while(current_Class_Rating > 5 || current_Class_Rating < 0) {
System.out.println("Sorry, but you can only give a rating of 0-5.");
System.out.println("How many plus signs does " + current_Class_Name + " get?");
current_Class_Rating = Integer.parseInt(in.nextLine());
}
// * TODO
// * Add to STRING and INTEGER LISTS.
}
可能存在某种调用顺序问题,因为字符串在进入while循环时为“空”。 对不起,有什么格式问题
谢谢你的帮助
注意:我通常使用C#,据我记忆所及,while循环将尝试在完成整个迭代之前检测条件情况
编辑:if语句不是用来运行的,而是用来证明两件事:1)中断条件可以检测到,2)在给定时间中断
编辑:更新以显示考虑中的所有代码
# 1 楼答案
您的问题似乎是基于一种误解,
while
循环只会在条件重新计算为false
在顶部时终止(而不是在变量被更新的瞬间)然而,可以使提示、作业和评估同时发生。首先,创建一个助手方法。比如然后,将其与赋值(作为副作用)评估为赋值的事实结合使用;另外,请遵循标准的Java camel大小写命名约定。比如
# 2 楼答案
尝试将实现更改为: