Chris M Chris M - 2 months ago 17
Java Question

Output after sorting?

I am working on making a program that takes a phrase from the user and then puts counts the vowels and then displays all of the vowels in sorted ascending order according to their count.

Example of how it is supposed to look:

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


I think my code is fine except I really don't know what to do after "the vowels and their count is: after I sorted both the vowels and the counts

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]);
}
}


My output is totally wrong and messed up. I assume you need a for loop to print the array but my output is way off:

Enter a phrase!


aaaaaeeeeiiioou

The vowels and their count:

U 1


U 79


U 79


U 79

U 79


Please help me print this correctly?

Answer

See my comment in the code for your sorting:

    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
    }

As a note, problems like this are why you should never rewrite sorting yourself. There are libraries for that. It would be much cleaner to implement this using a map of char to int and just output the results based on highest count. However, the below should fix your immediate problem:

    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;
    }