Java - Why can't I use charAt() to see if a char equals another?

倖福魔咒の 提交于 2019-12-03 16:21:46
Madhawa Priyashantha
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

I was having the same problem, but I was able to solve it using:

if (str.substring(0,1).equals("x") )

the substring can be used in a loop str.substring(i, i + 1)

charAt(i).equals('x') will not work together

This works if ( String(fieldNames.charAt(4)) == "f" )

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!