java 结合 charAt 和 IgnoreCase?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28387134/
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
combining charAt and IgnoreCase?
提问by Razoll
(Beginner with java here),
(这里是java初学者),
I'm making a simple game where the user can type if he wants to play again or not. However, I want the game to keep replaying as long as he types yes, Yes or any combination of yes. So As long as the first letter is y
the game continues. Ex)
我正在制作一个简单的游戏,用户可以在其中输入是否要再次玩。但是,我希望只要他输入“是”、“是”或“是”的任意组合,游戏就可以继续重播。所以只要第一个字母是y
游戏就继续。前任)
Game Runs
游戏运行
} while(newGame.charAt (0) == 'y');
But I also want java to ignore if it is Y
or y
, I tried combining charAt(0) == 'y'
and IgnoreCase but couldn't figure it out.
但我也希望 java 忽略它是Y
还是y
,我尝试组合charAt(0) == 'y'
和 IgnoreCase 但无法弄清楚。
I know I could just do && 'Y'
, but seems like it is unnecessary code?
我知道我可以做&& 'Y'
,但似乎这是不必要的代码?
Thanks
谢谢
回答by Aasmund Eldhuset
A neat trick for case insensitivity is to simply convert to lowercase before you compare. The class Character
contains a number of useful functions for manipulating characters, so you can do this:
不区分大小写的一个巧妙技巧是在比较之前简单地转换为小写。该类Character
包含许多用于操作字符的有用函数,因此您可以这样做:
} while (Character.toLowerCase(newGame.charAt(0)) == 'y');
回答by 1Darco1
You should use the method String.startsWith
. Its name is explaining what it is doing. To ignore case sensitivity, you can use String.toLowerCase
(or toUpperCase
respectivly).
你应该使用方法String.startsWith
。它的名字解释了它在做什么。要忽略区分大小写,您可以使用String.toLowerCase
(或toUpperCase
分别使用)。
This will result in the following:
这将导致以下结果:
if (newGame.toLowerCase().startsWith("y")) {
// Play again
}
回答by Razib
Based on the logic you described here I think you should use ||
instead of &&
.
基于你在这里所描述的逻辑,我认为你应该使用||
代替&&
。
And for ignoring case sensitivity you can Use Character's class static method toUpperCase()
or toLowerCase()
. Example -
对于忽略大小写敏感,您可以使用Character的类静态方法toUpperCase()
或toLowerCase()
. 例子 -
while(Character.toUpperCase(newGame.charAt (0)) == 'Y'){
...
...
...
}
回答by Pallav
You could ignore the case sensitivity by simply converting the character to lower case or upper case using toLowercase()
or toUppercase()
methods.
您可以通过简单地使用toLowercase()
或toUppercase()
方法将字符转换为小写或大写来忽略区分大小写。
while(Character.toLowerCase(newGame.charAt(0)) == 'y');
while(Character.toUpperCase(newGame.charAt(0)) == 'y');