使用Java的第一天,当我将数组索引添加到变量minIndex时,我在for循环中收到错误。我不确定将什么放入()中的值。我试过我,但那不起作用,由于我缺乏java知识,我不确定。我可以请一些指导。
public static int minPosition(double[] list) {
double leastNum;
leastNum = list[0];
// leastNum starts at first number in array
int minIndex;
minIndex = 1;
// minIndex starts at 1 as if first number in Array happens to be the lowest, its index will be one
for ( int i = 0; i < list.length; i++)
if (list[i] < leastNum)
leastNum = list[i];
minIndex = list.indexof(i);
return minIndex;
答案 0 :(得分:1)
i
是索引。
变化
minIndex = list.indexof(i);
到
minIndex = i;
您还应该更改
minIndex = 1;
到
minIndex = 0;
因为数组的第一个索引是0。
如评论所述,你有一些缺少花括号。这是完整的代码:
public static int minPosition(double[] list) {
double leastNum = list[0];
// leastNum starts at first number in array
int minIndex = 0;
// minIndex starts at 0 as if first number in Array happens to be the lowest, its index will be one
for ( int i = 0; i < list.length; i++) // you can also start with i = 1
// since you initialize leastNum
// with the first element
if (list[i] < leastNum) {
leastNum = list[i];
minIndex = i;
}
return minIndex;
}
答案 1 :(得分:0)
原始数组indexof()
中没有这样的方法:
public static int minPosition(double[] list) {
int minIndex = 0;//replaced
double leastNum = list[minIndex];//replaced
for ( int i = 1; i < list.length; i++) {//braces recommended, also `i` starts with `1`
if (list[i] < leastNum) {//braces required, since you have more than one line to execute
leastNum = list[i];
minIndex = i;//replaced
}
}
return minIndex;
}