【问题标题】:Switch Statement and While LoopSwitch 语句和 While 循环
【发布时间】:2013-12-20 01:49:47
【问题描述】:

我正在编写一个数据库程序,允许用户搜索员工并为他们打开一个菜单。在我的 Main() 中,我必须提示用户按 m 打开 menu() 或 q打开 finalStats() 任何其他输入都是无效的。我的问题是我无法让while循环正常工作。每当我按 m 时它都可以工作,当我按 q 时它工作正常,但是每当我按其他键时都会出现无限循环,它只会无限打印出“请输入有效字符”

boolean end = false;
    System.out.println("Enter m or M to open menu, otherwise enter q or Q for the final stats");
    String entered = scan.next();
    while (end == false)
    switch(entered)
    {
    case "m":
    case "M":
        menu();
    case "q":
    case "Q":
        finalStats();
        end = true;
    default:
        System.err.println("Please enter a valid character");
    }

【问题讨论】:

  • while (end == false) 最好写成while (!end)

标签: java while-loop switch-statement do-while


【解决方案1】:

我认为这可以解决您的问题:

boolean end = false;
System.out.println("Enter m or M to open menu, otherwise enter q or Q for the final stats");
String entered = scan.next();
while (end == false)
{
switch(entered)
    {
    case "m":
    case "M":
        menu();
        break;
    case "q":
    case "Q":
        finalStats();
        end = true;
        break;
    default:
        System.err.println("Please enter a valid character");
        break;
    }
    System.out.println("Enter m or M to open menu, otherwise enter q or Q for the final                     stats");
    String entered = scan.next();
}

你有几个问题。在您的情况下,您缺少 break; 并且您没有在 while 循环内请求新的输入。我不确定您是否要多次征求选择权。

【讨论】:

    【解决方案2】:

    您的switch case 中缺少break 语句。同时移动您的while 语句以允许用户扫描。

    试试这个:

    boolean end = false;
    while (end == false)
        System.out.println("Enter m or M to open menu, otherwise enter q or Q for the final stats");
        String entered = scan.next();
    
        switch(entered)
        {
        case "m":
        case "M":
            menu(); 
            break;
        case "q":
        case "Q":
            finalStats();
            end = true;
            break;
        default:
            System.err.println("Please enter a valid character");
        }
    

    【讨论】:

      【解决方案3】:

      你需要移动线

      while (end == false)
      

      scan.next()之前,让用户重试。确保在执行此操作时添加大括号,以便while 影响您正在显示的整个程序 sn-p。对于循环和 if 语句,始终使用花括号被认为是一种很好的做法。

      此外,正如@RahulTripathi 指出的那样,您需要在case 块的末尾添加break 语句。

      【讨论】:

      • 哇,我真笨,哈哈谢谢伙计,它现在工作正常,非常感谢:)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-16
      • 2023-04-10
      • 2013-04-13
      • 2023-03-03
      • 2021-03-08
      • 2013-10-21
      相关资源
      最近更新 更多