假设我有以下代码:
String myString = "Hello";
char firstChar = myString.charAt(0);
然后我想检查 firstChar 是否具有值“B”。我试过了
if(myChar == "b")
和
if(myChar.equals("b"))
但这些都不起作用。
我可以使用什么解决方案?
提前致谢!
假设我有以下代码:
String myString = "Hello";
char firstChar = myString.charAt(0);
然后我想检查 firstChar 是否具有值“B”。我试过了
if(myChar == "b")
和
if(myChar.equals("b"))
但这些都不起作用。
我可以使用什么解决方案?
提前致谢!
"b"
is not char but string to compare char you should write if(myChar == 'b')
Note:
5 means number
'5' means char
"5" means string
all are different datatypes.
read: How do I compare strings in Java?
==
compares reference equality. and .equals()
tests for value equality.
read also this to check for upper or lower char: Find if first character in a string is upper case, Java
Use 'B'. Java is case sensitieve, and you neer to compare a char
instead of String
You need to use the char literal by ':
if(myChar == 'b')
quotes(") represent strings. apostrophes(') represent characters
Characters work differently than String
. You can't call methods on them, but you can compare them using ==
.
If you want to compare either case, then you can use this:
if(myChar == 'b' || myChar == 'B')