java charat()没用,Java-为什么我不能使用charAt()来查看一个字符是否等于另一个?...

I want to see if a character in my string equals a certain other char value but I do not know what the char in the string is so I have used this:

if ( fieldNames.charAt(4) == "f" )

But I get the error:

"Operator '==' cannot be applied to 'char', 'jav.lang.String'"

But "g" == "h" seems to work and I know you can use '==' with char types.

Is there another way to do this correctly?

Thanks!

解决方案

if ( fieldNames.charAt(4) == 'f' )

because "f" is a String and fieldNames.charAt(4) is a char. you should use 'f' for check char

"g" == "h" works because both g and h are Strings

and you shouldn't use "g" == "h" you should use "g".equals("h") instead .

you can use == for primitive data types like char,int,boolean....etc.but for the objects like String it's really different.

To know why read this

but you can use also

'g' == 'h'

you should wrap Strings by double quotation and char by single quotation

String s="g";

char c='g';

but char can only have one character but String can have more than one

String s="gg"; valid

char c='gg'; not valid

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值