0

In this segment of code i am searching an Array list with the contents of:

[1,1,2,1,2,1,1,1,1,1,1,1,1,1,1]

I wrote the code to find the indices of the highest values in the ArrayList and then append those indices to a new Arraylist called

int high = findRelevance.get(0);
ArrayList<Integer> IndicesOfHighest = new ArrayList();
for (int iiii = 0; iiii < findRelevance.size(); iiii++)
{
    if (findRelevance.get(iiii) > high)
    {
        IndicesOfHighest.clear();
        IndicesOfHighest.add(iiii);

    }
    if (findRelevance.get(iiii) == high)
    {
        IndicesOfHighest.add(iiii);
    }
}

I would expect to get in return: [ 2, 4 ] but i instead get:

[4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]

2 Answers 2

1
  1. You are never updating high.
  2. Because there is no else if clause, if you fix that, you'd end up getting [2, 2, 4].

More generally, learn to debug. Programmers don't, as a rule, turn into infallible machines. Use a debugger, or if you don't have the time or the patience to learn how to use one, add a ton of System.out.println statements: The idea is to follow along with the code and calculate, using pen and paper or in your head, what the code should be doing. The moment where you find a discrepancy between what you think should happen and what actually happens? You found a bug, and usually enough context to know what's going wrong.

Sign up to request clarification or add additional context in comments.

1 Comment

it has been a long night of coding, thank you very much!!
0

[1,1,2,1,2,1,1,1,1,1,1,1,1,1,1]

int high = findRelevance.get(0);

i.e high = 1. You never updated the value of high. So,

 if (findRelevance.get(iiii) == high)

Due to above line whenever findRelevance.get(iii) == 1 (high is always 1), this if block gets executed.

Thus, you want to update your value of high when its 2.

int high = findRelevance.get(0);
    ArrayList<Integer> IndicesOfHighest = new ArrayList();
    for (int iiii = 0; iiii < findRelevance.size(); iiii++)
    {
        if (findRelevance.get(iiii) > high)
        {
            IndicesOfHighest.clear();
            IndicesOfHighest.add(iiii);
            high = findRelevance.get(iii); //added line


        }
        if (findRelevance.get(iiii) == high)
        {
            IndicesOfHighest.add(iiii);
        }
    }

1 Comment

it has been a long night of coding, thank you very much!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.