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