[英]Java do while loop doesn‘t stop when condition is false
即使 while 中的 boolean 为假,循环仍然继续。 我不确定出了什么问题。 boolean 循环变量应该设置为 false 如果他们的答案没有被缓存将您从循环中释放,但由于某种原因,程序没有这样做。
public static double getvalue(String unit) {
double answer = 0;
boolean loop = true;
do {
try {
System.out.println("enter the " + unit);
answer = sc.nextDouble();
loop = false;
} catch (Exception e) {
System.out.println("has to be a double");
sc.nextLine();
}
} while (loop);
return answer;
}
*编辑:在第 11 次查看我的代码并完成更多代码后,事实证明问题出在顶部的另一个循环中,我没有正确解决它,使其不断地一遍又一遍地调用这个循环。 我修复了它,现在它可以工作了。 非常感谢你,对此感到抱歉
这就是我要做的——
public static double getValue(String unit) {
Scanner keys = new Scanner(System.in);
double answer = 0;
System.out.println("Enter a double: ");
while (true) {
try {
answer = keys.nextDouble();
return answer;
} catch (Exception exc) {
System.out.println("number has to be a double!");
keys.nextLine();
}
}
}
试试这个方法:
public static double getvalue(String unit) {
double answer = 0;
boolean loop = true;
do {
try {
System.out.println("enter the " + unit);
answer = (double) sc.nextDouble();
break;
} catch (Exception e) {
System.out.println("has to be a double");
sc.nextLine();
}
} while (true);
return answer;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.