2016-01-10 15 views
-2
String at = "123123"; 
     for (int i = 0; i <at.length() ; i++) { 
      if (at.charAt(i)==1){ 
       int count=0; 
       count++; 
      } 
     } 

Want 1出現2次。我失敗的地方。謝謝。嘗試查找字符串的計數數字

+3

'詮釋計數= 0;'應放在外面的for循環。 – Tunaki

+3

你的問題在這裏'at.charAt(i)== 1'。你不應該比較一個字符與這樣的int。使用'at.charAt(i)=='1''或'at.charAt(i)== 49'。那Tunaki說:D – Tom

+0

**謝謝你們!:) ** –

回答

2
String at = "123123"; 
int count = 0; // Move out 
for (int i = 0; i < at.length(); i++) { 
    if (at.charAt(i) == '1'){ // Compare with the char '1' 
    count++; 
    } 
} 
// count is 2 here. 
0
String at = "123123"; 
    int count = 0;//outside the loop 
    int oneDigitCount = 0; 
    for (int i = 0; i < at.length(); i++) { 
     if (Character.isDigit(at.charAt(i))) {//digit count 
      count++; 
     } 
     if(at.charAt(i)=='1'){//count ones in string 
      oneDigitCount++; 
     } 
    } 
+0

而且? ...是你的答案「6」(這不正確)或「1」? – Tom

+0

您正在計數的位數,而不是'1'發生。 – Guy

+0

我以爲你想計算一個字符串中的數字。對不起 –