【发布时间】:2022-11-28 20:17:16
【问题描述】:
public class Menu {
public static void main(String[] args)
throws java.io.IOException {
char choice;
do {
System.out.println("Help on:");
System.out.println(" 1. if");
System.out.println(" 2. while");
System.out.println(" 3. do-while");
System.out.println(" 4. for");
System.out.println(" 5. switch");
choice = (char) System.in.read();
} while(choice < '1' || choice > '5');
}
}
当我输入 0 或大于 5 时,它会导致循环执行三次。像这样:
Help on:
1. if
2. while
3. do-while
4. for
5. switch
6
Help on:
1. if
2. while
3. do-while
4. for
5. switch
Help on:
1. if
2. while
3. do-while
4. for
5. switch
Help on:
1. if
2. while
3. do-while
4. for
5. switch
我该如何解决这个问题?
【问题讨论】:
-
检查 while 条件
-
输入将是
6,后跟 CR 和 LF 字符,因此在它再次从控制台读取之前,您将循环 3 次。 -
System.out.printf("choice = 0x%x.%n", (int)choice);你也会发现`"\r\n"。 -
考虑使用 Scanner 类