2

假设我有以下代码:

String myString = "Hello";
char firstChar = myString.charAt(0);

然后我想检查 firstChar 是否具有值“B”。我试过了

if(myChar == "b")

if(myChar.equals("b"))

但这些都不起作用。

我可以使用什么解决方案?

提前致谢!

4

4 回答 4

3

"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

于 2013-04-13T19:43:52.910 回答
0

Use 'B'. Java is case sensitieve, and you neer to compare a char instead of String

于 2013-04-13T19:43:38.277 回答
0

You need to use the char literal by ':

if(myChar == 'b')

quotes(") represent strings. apostrophes(') represent characters

于 2013-04-13T19:45:12.327 回答
0

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')
于 2013-04-13T19:46:12.737 回答