I have a String array with an index of 25. I have entered 25 elements, and I'm trying to display them, however, I only want the elements listed once, then the number of occurrences. Thus far, the number of occurrences is correct, but each iteration of the array is still printing multiple times. I am using a brute force method since I cannot use an ArrayList, Map, etc. Is there anyone who could give me hints to the logic of only printing the elements once? Here is the method below:
private void displayFlowers(String flowerPack[]) {
// TODO: Display only the unique flowers along with a count of any duplicates
/*
* For example it should say
* Roses - 7
* Daffodils - 3
* Violets - 5
*/
for(int i = 0; i < flowerPack.length; i++) {
int count = 0;
for(int j = 0; j < flowerPack.length; j++) {
if(flowerPack[i].equals(flowerPack[j]))
{
count++;
}
}
System.out.println(flowerPack[i] + " - " + count);
}
And here is the output to see what I'm am talking about:
rose - 6
daffodil - 2
rose - 6
daisy - 3
tulip - 2
wildflower - 3
lily - 3
lily - 3
daisy - 3
rose - 6
wildflower - 3
rose - 6
lilac - 1
daffodil - 2
rose - 6
lily - 3
tulip - 2
wildflower - 3
daisy - 3
rose - 6
carnation - 1
orchid - 1
sunflower - 3
sunflower - 3
sunflower - 3
1: Add an item to the pack.
2: Remove an item from the pack.
3: Sort the contents of the pack.
4: Search for a flower.
5: Display the flowers in the pack.
0: Exit the flower pack interface.
Yes, I typed rose 6 times, but I only want it to display it as:
rose - 6
daffodil -2
daisy - 3
tulip - 2
etc
etc
I know brute force does not do well in actual production, but we are learning how to manually force output, even if it is O(n^2) complexity. We'll get into the quicker stuff later.
ArrayList,Mapetc.? ASetsounds like exactly what you're looking for.