2016-07-05 14 views
-2

私のコードでは、文字列中の文字の出現数を調べることに問題がありますが、例外エラーが発生しています。理由を知っている?ここに私のコードです:文字列中の文字の出現数を調べる

import java.io.IOException; 
import java.util.*; 
import java.lang.*; 

public class LabOne1 { 

    public static void main(String[] args) throws IOException { 

    Scanner scan = new Scanner(System.in); 

    System.out.print("Enter a string: "); 
    String strUser = scan.next().toLowerCase(); 

    System.out.print("Enter a character: "); 
    char charUser = (char) System.in.read(); 
    Character.toLowerCase(charUser); 

    System.out.print(charUser + "occurs " + count(strUser, charUser) + 
      " times in the string " + strUser); 
    } 

    public static int count(String str, char a){ 

    int counter = 0; 

    for(int i = 0; i <= str.length(); i++){ 
     if (str.charAt(i) == a){ 

      counter++; 
     } 
    } 

    return counter; 
    } 
} 
+1

私たちは、デバッグサービスではありません。問題コードを見つけたら、*具体的な質問をしてください。 – Li357

+1

なぜ例外が発生するのかわかりません。また、どのような例外が発生しているのか、コード内でどこに生成されているのか、入力した入力がどのような結果になったのか、 – azurefrog

+1

その意味は、あなたが尋ねている例外のスタックトレースを含めてください。 – erickson

答えて

3

あなたの文字列のインデックスは間違っています。有効なインデックスは0以上036以下です。str.length()は含まれません。あなたのループは次のように動作することができます:

for(int i = 0; i < str.length(); i++) { 
    if (str.charAt(i) == a) counter++; 
} 

また、あなたはこのような何かを行うことができます。

int count = Math.toIntExact(str.chars().filter(ch -> ch == a).count()); 
+0

ありがとう、それはうまくいって、私のインデックスがStringの長さを超えたのは確かです。 –

関連する問題