Java-为什么我不能使用charAt()来查看一个字符是否等于另一个? [英] Java - Why can't I use charAt() to see if a char equals another?

查看:227
本文介绍了Java-为什么我不能使用charAt()来查看一个字符是否等于另一个?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想查看字符串中的字符是否等于某个其他char值,但是我不知道字符串中的char是什么,所以我使用了以下方法:

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" )

但是我得到了错误:

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

但是 g == h 似乎可行,我知道您可以将'=='与char类型一起使用。

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' )

因为 f String fieldNames.charAt(4) char 。您应该使用'f'作为支票字符

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

g == h 之所以起作用,是因为g和h都是 Strings

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

,因此您不应该使用 g == h 您应改用 g .equals( h)
可以将==用于原始数据类型,例如 char,int,boolean .... etc 。但是对于像String这样的 objects 来说,确实是不同的。
知道为什么要阅读这篇文章

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

,但您也可以使用

'g' == 'h' 

您应该用双引号括住字符串,用单引号括住字符

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

String s="g";

char c='g';

但是char只能有一个字符,而String可以有多个

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

String s="gg";  valid

char c='gg';  not valid

这篇关于Java-为什么我不能使用charAt()来查看一个字符是否等于另一个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆