0

I have no idea why this isn't working.

public static int getMaxPosition(ArrayList<Integer>list)
{
    int max=list.get(0);
    int maxPos=0;
    int curr;
    int c;
    for (c=0; c<list.size(); c++);
    {
        curr=list.get(c);
        if (curr>max);
        {
            maxPos=curr;
            max=curr;
        }
    }

    return maxPos;
}

This block of code gives a runtime error (IndexOutOfBoundsException) at the line curr=list.get(c);, and I can't find any good reason for it.

1
  • It'd be more idiomatic to go through the list with for (int curr : list) instead of messing around with an index.
    – millimoose
    Nov 7, 2012 at 19:17

3 Answers 3

4

You have a semi-colon after your for loop. So, it will execute till c < list.size(), and then it will exit when your c becomes list.size(). Now, your list.get(c) will get executed for that c = listsize, which is out of bounds.

for (c=0; c<list.size(); c++); <-- //Remove Semi-colon

Also, there is a semi-colon after your inner if: -

if (curr>max);  <-- // Remove this also.

NOTE: - It would be more readable for others and easier for you, if you iterate your list using enhanced for-loop: -

for (int curr: list) {
   if (curr>max) {
       maxPos=curr;
       max=curr;
   }
}
2
  • There is another semi-colon after the "if" statement that needs to be removed Nov 7, 2012 at 19:13
  • 3
    These kinds of error you can easily remove if you pass your code through a debugger.
    – Rohit Jain
    Nov 7, 2012 at 19:15
1

You have a semicolon after your for-loop, and then the block brackets. The semicolon causes the loop to excute, and then it drops into the block. The for-loop increments c to c == list.size(), and then drops into the execution block.

This is the working code:

public static int getMaxPosition(ArrayList<Integer>list)
{
    int max=list.get(0);
    int maxPos=0;
    int curr;
    int c;
    for (c=0; c<list.size(); c++)
    {
        curr=list.get(c);
        if (curr>max)
        {
            maxPos=curr;
            max=curr;
        }
    }

    return maxPos;
}
1
  • if (curr>max); Do You think It's Correct?
    – Parth Soni
    Nov 7, 2012 at 19:18
1
for (c=0; c<list.size(); c++);

 if (curr>max);

Remove semi-colon. Semi-colon ends the statement.

Your code should be something like below:

for (c=0; c<list.size(); c++)
{
curr=list.get(c);
        if (curr>max)
        {
            maxPos=curr;
            max=curr;
        }
...

}

0

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.