我正在制作一个程序,该程序从用户那里获取一个短语,然后对元音进行计数,然后根据计数按升序排列显示所有元音。
它的外观示例:
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
我认为我的代码很好,除非我真的不知道在&#34之后要做什么;元音和它们的数量是:在我对元音和计数进行排序之后
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
请帮我正确打印?
答案 0 :(得分:0)
在您的排序代码中查看我的评论:
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; // this line is wrong. reference vArray not vCount
}
作为一个注释,这样的问题是你不应该自己重写排序的原因。有图书馆。使用char到int的映射来实现它会更加清晰,只需根据最高计数输出结果。但是,以下内容应该可以解决您的问题:
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];
vArray[i+1] = temp2;
}