我不知道为什么这不起作用。
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;
}
此代码块在 curr=list.get(c);
行给出了运行时错误 (IndexOutOfBoundsException),但我找不到任何好的理由。
最佳答案
for
后面有一个分号环形。
所以,它会执行到 c < list.size()
,然后当你的 c
时它将退出变成list.size()
。现在,您的list.get(c)
将因此被执行c = listsize
,超出范围。
for (c=0; c<list.size(); c++); <-- //Remove Semi-colon
此外,内部 if 后面有一个分号:-
if (curr>max); <-- // Remove this also.
注意:-如果您迭代 list
,对其他人来说会更容易阅读,对您来说会更容易使用enhanced for-loop
:-
for (int curr: list) {
if (curr>max) {
maxPos=curr;
max=curr;
}
}
关于java - 非常简单的for循环错误Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13276512/