私は、文字列内の文字の発生を表示したいです。どのように私は私のコードを向上させることができますか?

user10369729:

私は、文字列内の文字の出現回数を表示し、また、それらをカウントするプログラムを作成したいです。今のコードは、単に文字を数えます。

私は、次の変更をしたいです:

1)どのように私はこのプログラムを作るのですかだけのように、文字の1種類を数えるaか、c文字列にI love ice cream

2)私は、文字列に文字を印刷するにはどうすればよい、の2があるとしましょうd、私のプログラムは、その後2が表示されますd最初。

3)に関してはScanner input = new Scanner(System.in);、私は私の日食でエラーが出る部分、スキャナがタイプに解決することはできないと言います。

また、コードを向上させることには何の必要性についてはコメントして自由に感じます。基本的には単なる文字列内のすべてのCを表示し、文字列の出現をカウントする単純なプログラムをしたいです。私は、私は、Javaを学ぶことができるので、それを変更し、自分のコードの周りに、その後の混乱にしたいです。

だから、これはこれまでのところ私のコードです:

public class Count { 
    static final int MAX_CHAR = 256; //is this part even needed?

    public static void countString(String str) 
    { 
        // Create an array of size 256 i.e. ASCII_SIZE 
        int count[] = new int[MAX_CHAR]; 

        int length = str.length(); 

        // Initialize count array index 
        for (int i = 0; i < length; i++) 
            count[str.charAt(i)]++; 

        // Create an array of given String size 
        char ch[] = new char[str.length()]; 
        for (int i = 0; i < length; i++) { 
            ch[i] = str.charAt(i); 
            int find = 0; 
            for (int j = 0; j <= i; j++) { 

                // If any matches found 
                if (str.charAt(i) == ch[j])  
                    find++;                 
            } 

            if (find == 1)  
                System.out.println("Number of Occurrence of " + 
                 str.charAt(i) + " is:" + count[str.charAt(i)]);             
        } 
    } 
    public static void main(String[] args) { 
        Scanner input = new Scanner(System.in); 
        String str = "geeksforgeeks"; 
        countString(str); 
    } 
} 
ムハンマド・ラヒムTaheri:

これを試して

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    String str = input.nextLine();

    // Whatever is the input it take the first character.
    char searchKey = input.nextLine().charAt(0);
    countString(str, searchKey);
}

public static void countString(String str, char searchKey) {
    // The count show both number and size of occurrence of searchKey
    String count = ""; 
    for (int i = 0; i < str.length(); i++) {
        if (str.charAt(i) == searchKey)
            count += str.charAt(i) + "\n";
    }
    System.out.println(count + "\nNumber of Occurrence of "
                    + searchKey + " is " + count.length() + " in string " + str);
}

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=222915&siteId=1