【问题标题】:Why a loop is running three time in eclipse when the condition is false?当条件为假时,为什么循环在 Eclipse 中运行三次?
【发布时间】: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 类

标签: java eclipse loops


【解决方案1】:

你的 while 语句有点错误,你试图将 > 和 < 与 char 一起使用,但使用 Scanner 类时效果不佳,你可以使用它来获取下一个 int,然后你可以在 while 语句中使用它。

Scanner scan = new Scanner(System.in);
int 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 = scan.nextInt();
} while (choice >= 1 && choice <= 5);

【讨论】:

    猜你喜欢
    • 2017-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-30
    • 2016-01-09
    • 2017-03-15
    • 1970-01-01
    • 2020-12-10
    相关资源
    最近更新 更多