0

これまでのところ、これは私が試したことです:

public class CharacterCounter {

public static void main(String[] args){

    String string = "sashimi";

    int count = 0;
    for(int i =0; i < string.length(); i++){
        if(string.charAt(i) == 'i'){
            count++;
            }
    }

    System.out.println("The number of letter i is " + count);

} 
}

出力:

 The number of letter i is 2

しかし、私がやりたいことは、プログラムが最も出現した文字をカウントすることです。

たとえば、文字列がSASHIMIの場合、出力は次のようになります。

 the number of letter S is 2
 the number of letter I is 2

私はこの問題で立ち往生しています。あなたの助けが必要です。ありがとう。

4

11 に答える 11

2

を使用するよりもプリミティブを使用する方が速いと思いますHashMapこれは機能します:

public static void main(String[] args)
{
    final String string = "sashimi";
    final int counters[] = new int[256]; // assuming you would use only ASCII chars
    for (final char c : string.toCharArray())
    {
        counters[c]++;
    }
    int maxCounter = 0;
    for (final int counter : counters)
    {
        if (maxCounter < counter)
        {
            maxCounter = counter;
        }
    }
    for (int i = 0; i < counters.length; i++)
    {
        if (counters[i] == maxCounter)
        {
            System.out.printf("%c has %d occurences.\n", i, counters[i]);
        }
    }
}

出力:

i has 2 occurences.
s has 2 occurences.
于 2013-08-01T13:33:07.490 に答える
1

TreeSet を作成することをお勧めします。次に、文字と出現回数を格納する新しいクラスを作成し、そのクラスに出現をチェックする compareTo と文字をチェックする equals を持たせることができます。次に、それらをツリーセットに挿入するたびに、常に最も多く出現した順序になります。

これについて助けが必要な場合、またはこの情報で解決できる場合はお知らせください:)

編集: TreeSet にすべての文字を入力したら、取り出した文字の出現回数が以前の文字数よりも少なくなるまで、文字を 1 つずつ取り出していきます (つまり、上の 3 文字が 3 回表示され、4 番目の文字が 2 回表示された場合は、最初の 3 文字のみを表示します)。

于 2013-08-01T13:23:00.453 に答える
0

import java.util.*;

public class CharacterCount {

public static void main(String[] args){

String string = "sashimi";
int count = 0;
ArrayList<Character> c = new ArrayList<Character>();
for(int i =0; i <string.length(); i++)
{
    count=0;
    if(c.contains(string.charAt(i)))
    {
        continue;
    }   
    c.add(string.charAt(i));        
    for(int j = 0;j<string.length();j++)
    {

        if(string.charAt(j) == string.charAt(i))
        {

            count++;

        }


    }
    System.out.println("The number of letter "+string.charAt(i)+" is " + count);
}

} }

于 2013-08-01T13:33:47.120 に答える