我有下面的Java代码。数组索引打印错误值
import java.util.Arrays;
public class Cook {
public static void main(String[] args) {
int num[] = { 3, 1, 5, 2, 4 };
getMaxValue(num);
}
public static void getMaxValue(int[] num) {
int maxValue = num[0];
int getMaxIndex = 0;
for (int i = 1; i < num.length; i++) {
if (num[i] > maxValue) {
maxValue = num[i];
}
}
getMaxIndex = Arrays.asList(num).indexOf(maxValue);
System.out.println(getMaxIndex + " and " +maxValue);
}
}
在上面的代码我试图找回在阵列中,最大值也是它的索引,但在这里,我得到的输出是
-1 and 5
返回的最大值很好,但不知道索引有什么问题。这应该实际上打印2
,但它是打印-1
,请让我知道我哪里出错了,我该如何解决这个问题。
Thankd
你真的需要数组... indexOf在这段代码中吗? –
如果你花时间做一点调试,并检查你使用的2(!)函数中的每一个函数都做了什么,你就会知道。 – njzk2