有没有办法在排序后的数组输出中附加字符标签?

Is there a way to attach a character label with a sorted array output?

我必须创建一个元音计数器和排序器,有人可以在其中输入单词或短语,然后程序会挑选、计算和排序元音。我有代码来计算和排序变量并向用户显示它们的计数,但它没有说明哪个元音有哪个计数,我已经用尽了所有资源。我对编码很陌生,知道的很少,所以如果有任何人可以提供帮助,我将不胜感激。

int[] vowelcounter = {a, e, i, o, u}; //This is the count of the vowels after reading the input.
   boolean hasswapped = true;
    while(hasswapped)
    {
        hasswapped = false;
        for(int j = 0; j<vowelcounter.length; j++)  
            {
            for(int k = j+1; k<vowelcounter.length; k++)
                {
                    if(vowelcounter[j] > vowelcounter[k])
                    {
                        int temp = vowelcounter[j];
                        vowelcounter[j] = vowelcounter[j+1];
                        vowelcounter[j+1] = temp;
                        hasswapped = true;
                    }
                }
            }
    }
        
        for(int j=0; j<vowelcounter.length; j++)
            {   
                    System.out.println(vowelcounter[j]);
            }

你可以使用一种叫做 HashMap 的东西

HashMap<String, Integer> vowelCounts = new HashMap<>();

要向其中添加数据,只需执行以下操作:

vowelCounts.put("a", 1); // The vowel "a" is once in the sentence
vowelCounts.put("e", 2); // The vowel "e" is 2 times in the sentence

打印到控制台:

for(String vowel : vowelCounts.keySet() ) {
     System.out.println(vowel + ": " + vowelCounts.get(vowel));
}

更多信息:click me!

有一个char[] vowels = { 'a', 'e', 'i', 'o', 'u' }。每次交换计数器时,在元音数组中进行相同的交换。

int temp = vowelcounter[j];
vowelcounter[j] = vowelcounter[j+1];
vowelcounter[j+1] = temp;
char temp2 = vowel[j];
vowel[j] = vowel[j+1];
vowel[j+1] = temp2;
hasswapped = true;

最后,在 vowelcounter[j] 旁边打印出 vowel[j];

代替 int 值来表示计数器,可以引入 class 来存储和打印元音字符及其计数:

class VowelCount {
    private final char vowel;
    private int count = 0;

    public VowelCount(char v) {
        this.vowel = v;
    }

    public void add() { this.count++; }

    public int getCount()  { return this.count; }

    public char getVowel() { return this.vowel; }

    @Override
    public String toString() { return "Vowel '" + vowel + "' count = " + count;}
}

然后创建并排序 VowelCount 的数组而不是 int[] count

VowelCount[] vowelcounter = {
    new VowelCount('a'), new VowelCount('e'), new VowelCount('i'), 
    new VowelCount('o'), new VowelCount('u')
};

排序可以使用标准方法 Arrays::sort 和自定义比较器而不是自制的冒泡排序来实现

Arrays.sort(vowelcounter, Comparator.comparingInt(VowelCount::getCount));

然后统计数据的打印如下(使用 for-each 循环以及覆盖的 toString):

for (VowelCount v: vowelcounter) {
    System.out.println(v); // print sorted by count
}

计算频率的更高级方法是使用元音与其频率的映射,并按计数值对映射进行排序。