2013-05-04 99 views
0

我已經從本網站上的一個很好的答案複製此代碼(計算字符串中的字符並返回計數),並已稍微修改它以適應我自己的需要。 但是,我似乎在我的方法中出現異常錯誤。計數字符方法異常錯誤?

我很感謝這裏的任何幫助。

請原諒我的代碼中的任何錯誤,因爲我仍在學習Java。

這裏是我的代碼:

public class CountTheChars { 

public static void main(String[] args){ 

    String s = "Brother drinks brandy."; 

    int countR = 0; 

    System.out.println(count(s, countR)); 

} 


public static int count(String s, int countR){ 

    char r = 0; 

    for(int i = 0; i<s.length(); i++){ 

     if(s.charAt(i) == r){ 

      countR++; 

     } 

     return countR; 

    } 

} 

} 

這裏是個例外:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
The method count(String) in the type CountTheChars is not applicable for the arguments (int) 

at CountTheChars.main(CountTheChars.java:12) 
+1

什麼是例外? – Makoto 2013-05-04 16:23:11

+0

我已在上面添加。 – PrimalScientist 2013-05-04 16:24:12

+1

我的猜測是你沒有重新編譯你的Eclipse項目。這樣做。 – Makoto 2013-05-04 16:26:30

回答

1

你缺少你的方法public static int count(String s, int countR) return語句。目前它不返回int如果s.length() == 0

這應該按預期工作:

public class CountTheChars { 

    public static void main(String[] args) { 

     String s = "Brother drinks brandy."; 

     int countR = 0; 

     System.out.println(count(s, countR)); 

    } 

    public static int count(String s, int countR) { 

     for (int i = 0; i < s.length(); i++) { 

      if (s.charAt(i) == 'r') { 

       countR++; 

      } 

     } 

     return countR; 

    } 

} 
+0

啊,明白了。 我的迴歸是在錯誤的地方。好地方,謝謝=] 其實,我已經修改了返回countR的地方,它已經刪除了錯誤,但是它返回0? – PrimalScientist 2013-05-04 16:30:53

+2

這是因爲你的條件'if(s.charAt(i)== r)'從來就不是真的。 – 2013-05-04 16:37:23

+0

我現在看到了。感謝您的幫助。它現在工作正常。 – PrimalScientist 2013-05-04 16:45:42

0

爲什麼你不能使用s.length()String s計數的字符數(字符串的長度即)?

編輯:更改爲納入「計數char r的發生次數」。您調用函數作爲count(s,countR, r)並宣佈char r = 'a'或任何char要在main

public static int count(String s, int countR, char r){ 

    countR= 0; 
    for(int i = 0; i<s.length(); i++){ 

     if(s.charAt(i) == r){ 

      countR++; 

     } 

     return countR; 

    } 

} 
+1

目標似乎是計算字符串中特定字符(看起來像'r'的數量)的出現次數,而不是字符串的總長度。 – ajp15243 2013-05-04 16:40:39

+0

這是正確的。計算在字符串s中使用字符'r'的次數。 – PrimalScientist 2013-05-04 16:41:21

+0

更新了代碼。 – Bill 2013-05-04 16:48:30

1

2個問題:

  1. 做的s.charAt(我)比較時,您的計數方法是比較每個在單詞s中的字母給你設定爲0的變量r。這意味着,從技術上講,你的方法是記錄句子中出現數字0的次數。這就是爲什麼你得到0.要解決這個問題,刪除你的r變量,並在你的比較中,作爲比較s.charAt(i)=='r'。注意里約周圍的撇號意味着你特別提到了字符r。

  2. 您的計數方法不正確返回對於其中的字符串是什麼,這意味着將有一個長度爲零,這意味着你的循環沒有運行,你的方法將跳過以及return語句的情況下你有在那裏。要解決這個問題,所以無論你在什麼字符串,返回語句總是返回在方法的最底部移動return語句(因爲它應該,因爲你的方法需要將返回一個int)

+0

您已幫助解決我的問題。它的工作原理和感謝。 – PrimalScientist 2013-05-04 16:45:09

+0

不用擔心。如果你可以upvote這個答案,並選擇它作爲答案,這將是偉大的:) – micnguyen 2013-05-04 16:54:39