0
我正在製作一個程序,它需要從用戶那裏獲取一個短語,然後對元音進行計數,然後根據他們的計數以升序排列顯示所有元音。排序後輸出?
它應該是怎樣看例:
Welcome to the vowel counter and sorter!
Enter a phrase!
aaaaaeeeeiiioou
The vowels and their count:
u 1
o 2
i 3
e 4
a 5
我覺得我的代碼是正確的,除了我真的不知道「元音後做什麼,他們的數量是:我都整理後。元音和計數
int[] vCount = new int[5];
System.out.println("Welcome to the vowel counter and sorter!\nEnter a phrase!");
String input = keyboard.nextLine();
String upInput = input.toUpperCase();
//examine all characters
for (int i=0; i<upInput.length(); i++)
{
switch (upInput.charAt(i))
{
case 'A':
vCount[0]++;
break;
case 'E':
vCount[1]++;
break;
case 'I':
vCount[2]++;
break;
case 'O':
vCount[3]++;
break;
case 'U':
vCount[4]++;
break;
}
}
char[] vArray = {'A', 'E', 'I', 'O', 'U'};
//Bubble Sort
boolean hasSwapped = true;
while (hasSwapped == true)
{
hasSwapped = false; //Assumes it is sorted
for (int i = 0; i<vCount.length-1; i++)
{
if (vCount[i] > vCount[i+1])
{
int temp = vCount[i];
vCount[i] = vCount[i+1];
vCount[i+1] = temp;
hasSwapped = true;
char temp2 = vArray[i];
vArray[i] = vArray[i+1];
vCount[i+1] = temp2;
}
}
}
System.out.println("The vowels and their count:");
for (int i=0; i<vArray.length; i++)
{
System.out.println(vArray[i]+ " " +vCount[i]);
}
}
我的輸出是完全錯誤的,搞砸了我想你需要一個for循環輸出數組,但我的輸出是路要走:
Enter a phrase!
aaaaaeeeeiiioou
The vowels and their count:
U 1
U 79
U 79
U 79
U 79
請幫我打印正確嗎?
哇太簡單了我很驚訝,我忽略了這一點!謝謝nhouser,我們剛開始學習數組,我的教授試圖讓我們學習的一個練習是使用「冒泡排序」對數組進行排序,這是我的第一個編程類,所以我對地圖和庫沒有任何瞭解! –
@ChrisM沒問題,很樂意幫忙。請註冊並接受! – nhouser9
會upvote並接受:)順便說一句,我用我的教授的例子排序代碼塊,你能告訴我爲什麼它是vCount.length -1的行:for(int i = 0; i