0

I'm trying to return the first index of the max value of an ArrayList<Integer>. The code below finds the second maximum instead of the first. How do I return the first max value encountered by the loop?

public int findIndexOfMax() {
    int maxIndex = 0;
    for (int k = 0; k < myFreqs.size(); k++) {
        if (myFreqs.get(k) > maxIndex) {
            maxIndex = myFreqs.get(k);
        }
    }
    return maxIndex;
}

What gets returned is 'test. 3'. But it should be the first max which is 3 for the letter 'a'.

Number of unique words: 7
1   this
1   is
3   a
3   test.
1   yes
1   test
1   of
The word that occurs most often and its count are: test. 3
2
  • 2
    What are you defining as the first max value in the loop? Commented Dec 31, 2017 at 5:15
  • You just use a HashMap for this, as seen here. Commented Dec 31, 2017 at 6:09

3 Answers 3

3

You seem to have forgotten to access the element at the maxIndex in your comparison. And you set the index to the value of the element in your if (instead of the index). I think you wanted,

public int findIndexOfMax() {
    int maxIndex = 0;
    for (int k = 1; k < myFreqs.size(); k++) {
        if (myFreqs.get(k) > myFreqs.get(maxIndex)) {
            maxIndex = k;
        }
    }
    return maxIndex;
}
Sign up to request clarification or add additional context in comments.

Comments

0

I think you are using the integers on the left as index for the Strings on the right and when you use 3 as index for the second time it is overlapping the value "a" with "test".

Comments

0

since there is a tie between "a" and "test." Frequencies, you want to return the first value which is "a" with the occurrence of 3

to do so, you need to find the max value and its position in myFreqs and then get the value of the other ArrayList containing the words at the index of the position of the max value.

int maxElement = 0;
int maxPosition = 0;
for(int i = 0; i < this.myFreqs.size(); i++){
    if(this.freqs.get(i) > maxElement){
        maxElement = this.freqs.get(i);
        maxPosition = i;
    }
}
return maxPosition;

now you can simply find the first most frequent word in the arrayList of the words:

words.get(maxFreq)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.