我有一个方法用于显示最高值,并显示它所属的索引号。到目前为止,它已经可以显示最高值,但索引号无法显示。我该怎么做才能让系统显示i
值呢?
private void pick_highest_value_here_and_display(ArrayList<Double> value) throws Exception {
// TODO Auto-generated method stub
double aa[]=value.stream().mapToDouble(v -> v.doubleValue()).toArray();
double highest=Double.MIN_VALUE;
System.out.println(highest);
for(int i=0;i<aa.length;i++)
{
if(aa[i]>highest)
{
highest=aa[i];
}
}
System.out.println(highest);
System.out.println(i); // Error: create local variable i
}
答案 0 :(得分:8)
您只需修改代码即可保存最大AND i
:
private void pick_highest_value_here_and_display(ArrayList<Double> value) throws Exception {
// TODO Auto-generated method stub
double aa[]=value.stream().mapToDouble(v -> v.doubleValue()).toArray();
double highest=Double.MIN_VALUE;
int index=0;
System.out.println(highest);
for(int i=0;i<aa.length;i++)
{
if(aa[i]>highest)
{
index=i;
highest=aa[i];
}
}
System.out.println(highest);
System.out.println(index);
}
答案 1 :(得分:3)
您还需要一个变量来存储最高变量的索引。
int highestIndex = 0;//Store index at some other variable
for(int i=0; i< aa.length; i++) {
if(aa[i] > highest) {
highest = aa[i];
highestIndex = i;
}
}
System.out.println("Highest value :"+highest+ " found at index :"+highestIndex);
答案 2 :(得分:2)
您还必须存储最高值的索引:
private void pick_highest_value_here_and_display(ArrayList<Double> value) throws Exception {
// TODO Auto-generated method stub
double aa[]=value.stream().mapToDouble(v -> v.doubleValue()).toArray();
double highest=Double.MIN_VALUE;
int highestIndex;
System.out.println(highest);
for(int i=0;i<aa.length;i++)
{
if(aa[i]>highest)
{
highest=aa[i];
highestIndex=i;
}
}
System.out.println(highest);
System.out.println(highestIndex); // Error: create local variablre i
}