![](/img/trans.png)
[英]Why can't I see the contents in Java char array neither in eclipse console nor in the debugger?
[英]Java - Why can't I use charAt() to see if a char equals another?
我想看看我的字符串中的一個字符是否等於某個其他字符值,但我不知道字符串中的字符是什么,所以我使用了這個:
if ( fieldNames.charAt(4) == "f" )
但我得到錯誤:
"Operator '==' cannot be applied to 'char', 'jav.lang.String'"
但是"g" == "h"
似乎可以工作,而且我知道你可以將'=='
與 char 類型一起使用。
還有另一種方法可以正確地做到這一點嗎? 謝謝!
if ( fieldNames.charAt(4) == 'f' )
因為"f"
是一個String
而fieldNames.charAt(4)
是一個char
。 你應該使用'f'
來檢查字符
"g" == "h"
有效,因為 g 和 h 都是Strings
並且你不應該使用"g" == "h"
你應該使用"g".equals("h")
代替。 您可以將 == 用於primitive
數據類型,例如char,int,boolean
....etc。但是對於像 String 這樣的objects
它確實不同。 要知道為什么讀這個
但你也可以使用
'g' == 'h'
你應該用雙引號包裹字符串,用單引號包裹字符
String s="g";
char c='g';
但 char 只能有一個字符,而 String 可以有多個
String s="gg"; valid
char c='gg'; not valid
我遇到了同樣的問題,但我能夠使用以下方法解決它:
if (str.substring(0,1).equals("x") )
子字符串可以在循環中使用 str.substring(i, i + 1)
charAt(i).equals('x') 不能一起工作
這有效:
if (String(fieldNames.charAt(4)) == "f")
.equals() 仍然可以使用,但您必須記住,字符需要撇號(') 而不是引號(")。例如: someChar.equals('c') 對字符有效,而 someString.equals("c ") 對字符串有效。
package code;
public class NoOfTimesTheNoAppearInGiven3 {
public static void main(String[] args) {
String n = "123242526";
int j =0;
for(int count = 0 ; count <n.length();count++) {
if(n.charAt(count)=='2') {
j=j+1;
System.out.println("Count: "+j );
}else {
System.out.println("not in this");
}
}
System.out.println("No of times digit 2 appared: "+j);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.