我从输入中读取的字符串会跳过所有开关案例并直接转到默认情况。当我执行String s = in.readLine()。trim()时,它会进入所有情况并打印每个案例,例如“HELLO”输入打印英语,俄语,德语等。
import java.io.IOException;
class Main implements Runnable {
public static void main(String[] args) {
Main main = new Main();
main.run();
}
@Override
public void run() {
ExecutorTemplate exe = new ExecutorTemplate();
exe.run();
}
}
class ExecutorTemplate implements Runnable {
@Override
public void run() {
String s = readLine();
int casenr = 1;
while(!s.equals("#")){
switch(s){
case "HELLO":
System.out.printf("Case %d: %s\n",casenr++,"ENGLISH");
case "HOLA":
System.out.printf("Case %d: %s\n",casenr++,"SPANISH");
case "HALLO":
System.out.printf("Case %d: %s\n",casenr++,"GERMAN");
case "BONJOUR":
System.out.printf("Case %d: %s\n",casenr++,"FRENCH");
case "CIAO":
System.out.printf("Case %d: %s\n",casenr++,"ITALIAN");
case "ZDRAVSTVUJTE":
System.out.printf("Case %d: %s\n",casenr++,"RUSSIAN");
default:
System.out.printf("Case %d: %s\n",casenr++,"UNKNOWN");
}
s = readLine();
}
}
从标准输入读取的方法
private String readLine() {
byte line[] = new byte[255];
int length = 0;
int input = -1;
try {
while (length < 255) {// Read until maxlength
input = System.in.read();
if ((input < 0) || (input == '\n')) {
break; // or until end of line ninput
}
line[length++] += input;
}
if ((input < 0) && (length == 0)) {
return null; // eof
}
return new String(line, 0, length);
} catch (IOException e) {
return null;
}
}
}
答案 0 :(得分:1)
问题是你忘记了休息声明。
有关中断的switch语句,请参阅此示例:
break;
select t1.user as user1, t2.user as user2, t3.user as user3
from
users_entities t1
left outer join users_entities t2
on t1.entity = t2.entity
left outer join users_entities t3
on t2.entity = t3.entity
where t1.user = 122
退出了switch语句。如果没有它,执行将继续执行,并转到下一个语句。