0

I've been trying to make and display in JFrame a top five out of 13 options. It goes something like this:

I have a .txt with a bunch of words, let's say apple, banana, orange, etc. And a counter for each word. Then I open the file and scan it with a Scanner and a String, if it finds the word "apple" then it adds 1 to the apple counter. After it scans the whole .txt I put the counters in an array and sort them with Arrays.sort(array);

My problem is that the array only holds the numeric value for each word, so I tried comparing the last position in the array (since it's the highest one) with every counter for each word, and if it matches with any counter I set that one as "Top 1", then I do the same for "Top 2" and the second-to-last in the array and so on.

But this obviously only works if there are no repeated values. If "Apple" and "Orange" both appear 3 times then both will match and then, the program will set the first one matched in the TextField1 and 2.

Is there a way to go around this? Maybe a way to display the variable name in the TextField instead of the value? or maybe a different data structure to keep both the name and the value of the variable?

Thanks in advance!

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433

2 Answers2

1

or maybe a different data structure to keep both the name and the value of the variable?

Ding ding! You want to use a map for this. A map stores a key and a value as a pair. To give you a visual representation, a map looks like this:

Cats: 5
Dogs: 3
Horses: 2

Using a map you can access both the key (name of the word you found) and its paired value (number of times you found it in your file)

How to use maps

TheFunk
  • 981
  • 11
  • 39
0

You might want to consider priority queue in java. But first you need a class which have 2 attributes (the word and its quantity). This class should implement Comparable and compareTo method should be overridden. Here's an example: https://howtodoinjava.com/java/collections/java-priorityqueue/

glennmark
  • 524
  • 3
  • 13