while循环检查字符输入

时间:2012-10-15 15:04:17

标签: java string loops while-loop character

我试图以角色的形式接受用户的输入。我有那个工作但我需要检查并确保它是6个字符之一(H,h,S,s,L,l)。我有一个while循环,但只要向它添加多个字符语句,循环就会为每个应该正确的值提供错误。

这是功能:

    private static char getHighLow(Scanner keyboard) 
{
    System.out.println("High, Low, or Sevens (H/L/S): ");
    String choiceString = keyboard.next();

    char choice = choiceString.charAt(0);

    while (choice != 'H' || choice != 'h' || choice != 'L' || choice != 'l' || choice != 'S' || choice != 's')
    {
        System.out.println("You have entered an invalid entry.");
        System.out.println("High, Low, or Sevens (H/L/S): ");
        choiceString = keyboard.next();
    }

    return choice;

}

继续检查这样的多个字符的最佳方法是什么?

3 个答案:

答案 0 :(得分:4)

使用&&代替||

while (choice != 'H' && choice != 'h' && choice != 'L' && choice != 'l' && choice != 'S' && choice != 's')

首先转换为小写可以简化这一过程。

choice = Character.toLowerCase(choice);

while (choice != 'h' && choice != 'l' && choice != 's')

答案 1 :(得分:3)

您的逻辑中存在错误:您应该使用AND连接这些测试:&&

while (choice != 'H' && choice != 'h' && choice != 'L' && ...

此外,choice永远不会在循环体内更新,因此它永远不会改变。在循环中重新阅读choice = choiceString.charAt(0);后重复choiceString

从概念上讲,只要字符不是H并且不是L且不是S ,您就要继续询问输入。

答案 2 :(得分:2)

您永远不会在choice循环中更新while

只需在循环结束时添加此行:

choice = choiceString.charAt(0);

此外,您应该使用&&而不是||进行核对。

相关问题