John Joe
John Joe

Reputation: 12803

Display highest value and index number in array

I have one method which used to display the highest value and also display which index number it belongs to. So far it already can display the highest value but the index number cannot be displayed. What should I do so that the system can display the i value also?

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
}

Upvotes: 2

Views: 464

Answers (3)

Erwan C.
Erwan C.

Reputation: 719

You just have to modify your code to save the max 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); 
}

Upvotes: 8

Akash Thakare
Akash Thakare

Reputation: 23002

You need one more variable to store the index of highest variable.

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);

Upvotes: 3

uoyilmaz
uoyilmaz

Reputation: 3105

You have to store the index of the highest value too:

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
}

Upvotes: 2

Related Questions