Java 不大于或等于 Char 类型的运算符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40646879/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java Not Greater than Or Equal to Operator for Char Type
提问by Majestic
So I'm trying to write this in a short way:
所以我试图用简短的方式写这个:
char letter;
while ( letter!='A' && letter!='B' && letter!= 'C... letter!= 'a'
&& letter !='b' && letter!=c)
Basically if the user does not input a letter between A and C, a while loop will run until A,B,C,a,b,c is inputted.
基本上,如果用户没有在 A 和 C 之间输入字母,while 循环将运行,直到输入 A、B、C、a、b、c。
It should be in the form of
它应该是这样的形式
while(letter<'a' && letter > 'c')
while(letter<'a' && letter > 'c')
but it didn't work apparently because if I inputted F, is it greater than 'C', but it is less than 'c', since char uses ACSII.
但它显然不起作用,因为如果我输入 F,它是否大于“C”,但小于“c”,因为 char 使用 ACSII。
回答by Erwin Bolwidt
There are many ways to do this check.
有很多方法可以进行此检查。
char letter;
while (!(letter >= 'A' && letter <= 'C') && !(letter >= 'a' && letter <= 'c'))
Or you can use Character.toUpperCase
or toLowerCase
on the letter first, to remove half of the conditions.
或者你可以先在字母上使用Character.toUpperCase
或toLowerCase
,去掉一半的条件。
Or, if the range of letters is small or non-contiguous, you could do:
或者,如果字母范围很小或不连续,您可以这样做:
char letter;
while ("ABCabc".indexOf(letter) == -1)
There are more ways of course.
当然还有更多的方法。
回答by Hovercraft Full Of Eels
Set letter to lower case and then check:
将字母设置为小写,然后检查:
letter = Character.toLowerCase(letter);
while (letter < 'a' && letter > 'c') {
// ...
}
This way, even if the user enters an upper case letter, the check will work.
这样,即使用户输入大写字母,检查也会起作用。
回答by user207421
You need two conditions and a bit of de Morgan:
你需要两个条件和一点德摩根:
while(!((letter >= 'A' && letter <= 'C') || (letter >= 'a' && letter <= 'c')))
回答by Scary Wombat
or good old regex
或好的旧正则表达式
char input = 'B';
Pattern p = Pattern.compile("a|b|c", Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher("" + input);
if (m.find())
{
System.out.println("found");
}
回答by S.S.Prabhu
You can check with ASCII code of characters such as 65 for 'A' and 97 for 'a'. So you could do if (letter > 65) to check if letter greater than 'A'. Hope this helps. Updates : For checking if letter is only either of A,B,C,a,b,c, use this check : if (letter >= 65 && letter <= 67) || (letter >= 97 && letter <= 99) . Please mark as answer if this helps.
您可以检查字符的 ASCII 码,例如 65 代表 'A' 和 97 代表 'a'。所以你可以做 if (let > 65) 来检查字母是否大于'A'。希望这可以帮助。更新:为了检查字母是否只是 A、B、C、a、b、c 中的任何一个,请使用此检查: if (letter >= 65 && letter <= 67) || (字母 >= 97 && 字母 <= 99)。如果这有帮助,请标记为答案。