只是想打破这个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)在给定时间爆发。
编辑:已更新为显示正在考虑的所有代码。
尝试将实现更改为:
String current_Class_Name = null;
Integer current_Class_Rating = null;
do {
// * Get class name.
System.out.println("What class are you rating?");
current_Class_Name = in.nextLine().trim();
try {
// * Get class rating.
System.out.println(String.format("How many plus signs does '%s' get?",current_Class_Name));
current_Class_Rating = Integer.parseInt(in.nextLine().trim());
}catch(NumberFormatException e) {
current_Class_Rating = null;
}
if((current_Class_Rating == null)||(!(current_Class_Rating>=0 && current_Class_Rating <=5))) {
System.out.println("Invalid rating value! Rating must be integer 0-5!");
continue; // skips back to beginning of the loop
}
// * TODO
// * Add to STRING and INTEGER LISTS.
}while(!current_Class_Name.equalsIgnoreCase("done"));
您的问题似乎是基于一个错误的观念,while
循环只会在条件重新评估为顶部的false
时才终止(而不是在更新变量的那一刻)。 但是,您可以完成,因此提示,任务和评估立即发生。首先,创建一个辅助方法。喜欢,
private static String promptForClassName(Scanner in) {
System.out.println("What class are you rating?");
return in.nextLine();
}
然后,将其与赋值(作为副作用)求值为赋值的事实一起使用;另外,please遵循标准的Java camel大小写命名约定。喜欢,
String currentClassName;
while (!(currentClassName = promptForClassName(in)).equalsIgnoreCase("Done")) {
String prompt = "How many plus signs does " + currentClassName + " get?";
// * Get class rating.
System.out.println(prompt);
int currentClassRating = 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 (currentClassRating > 5 || currentClassRating < 0) {
System.out.println("Sorry, but you can only give a rating of 0-5.");
System.out.println(prompt);
currentClassRating = Integer.parseInt(in.nextLine());
}
// * TODO
// * Add to STRING and INTEGER LISTS.
}
System.out.println("Detected 'Done'");