第二个print语句给出了编译时错误。请解释一下
public class mainClass {
public static void main(String args[]) {
final int a=10, b=20;
while(a < b) {
System.out.println("Hello");
}
System.out.println("World");
}
}
发布于 2018-06-10 00:28:33
条件a<b
始终保持为真。
编译器检测到您的程序永远不会结束,并且永远不会到达第二个打印行,因此它抛出编译错误
您可能希望将您的while
更改为if
检查
发布于 2018-06-10 00:43:07
你的代码可以写成:
public class Answer {
public static void main(String[] args) {
while (10 < 20) { //always true, so loop is infinite
System.out.println("Hello");
}
System.out.println("World"); //previous loop is infinite => this statement will never be reached
}
}
但是,如果你这样写:
public class Answer {
public static void main(String[] args) {
int a = 10, b = 20;
while (a < b) {
System.out.println("Hello");
b--; //if you decrease var b, in some point while condition becomes false
}
System.out.println("World"); //AND this statement will be reached
}
}
请注意,int b不可能是最终的!
https://stackoverflow.com/questions/50776306
复制相似问题