While循环检查字符输入 [英] While loop to check character input
问题描述
我正在尝试接受来自用户的字符形式的输入.我已经在工作,但是我需要检查并确保它是6个字符(H,h,S,s,L,l)之一.我有一个while循环,但是一旦添加了多个字符语句,循环就会为每个正确的值给出错误.
I am trying to accept input from the user in the form of a character. I have that working but I need to check and make sure it is one of 6 characters (H, h, S, s, L, l). I have a while loop but as soon as add more than one character statement to it, the loop gives the error for every value that should be correct.
这是函数:
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;
}
继续检查像这样的多个字符的最佳方法是什么?
What is the best way to continue checking for multiple characters like this?
推荐答案
您的逻辑中有一个错误:您应该将这些测试与AND连接:&&
:
There is an error in your logic: you should be connecting those tests with AND: &&
:
while (choice != 'H' && choice != 'h' && choice != 'L' && ...
此外, choice
永远不会在循环体内进行更新,因此它永远不会改变.在循环中重新读取 choiceString
后,复制 choice = choiceString.charAt(0);
.
Furthermore choice
is never being updated within the body of the loop, so it will never change. Duplicate the choice = choiceString.charAt(0);
after you re-read choiceString
within the loop.
从概念上讲,只要字符不是H AND不是L AND不是S ,您就希望继续要求输入.
Conceptually, you want to keep asking for input so long as the character isn't H AND isn't L AND isn't S.
这篇关于While循环检查字符输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!