【发布时间】:2015-09-27 19:54:22
【问题描述】:
我有一段时间没有使用 Java,遇到了一个简单但令人沮丧的错误。我的代码是这样的:
public static void main(String[] args) throws IOException{
String input = "";
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
while(input != "Q"){
input = in.readLine().toUpperCase();
switch(input){
default: break;
case "A": //do stuff break;
case "B": //do stuff break;
}
}
System.out.println("Out of the loop!"); //never reaches this statement
}
我运行了 eclipse 调试器,它清楚地显示输入变量在用户输入时被更改为“Q”,但 while 循环不断重新启动。
【问题讨论】:
-
你想
break退出switch语句还是跳到while循环的末尾?因为在后一种情况下,break以switch为目标,需要显式标签才能正常工作。
标签: java while-loop switch-statement