JSox
JSox

Reputation: 25

How to find index of max array value?

Here's what I have so far

 double[] num = {1.9, 2.9, 3.4, 3.5};
 double max = num [0];
    for (int i = 1 ; i < num.length ; i++)
    {
        if (num [i] > max)
            max = num [i]; 
    }
    System.out.println ("Max is " + max);

I need to find the index of the greatest value. I've tried printing the index by putting a sentence inside the if statement, and I've also tried by storing i into another variable. None of them worked.

Upvotes: 0

Views: 119

Answers (2)

JayC667
JayC667

Reputation: 2588

You need to keep track of the max value and its index.

public class GetMaxIndex {
    public static void main(final String[] args) {
        final double[] numbers = { 1.9, 2.9, 3.4, 3.5 };
        double maxNumber = numbers[0];
        int maxIndex = 0;
        for (int i = 1; i < numbers.length; i++) {
            if (numbers[i] > maxNumber) {
                maxNumber = numbers[i];
                maxIndex = i;
            }
        }
        System.out.println("Max is " + maxNumber);
        System.out.println("Index of max is " + maxIndex);
    }
}

Upvotes: 2

kusnaditjung tjung
kusnaditjung tjung

Reputation: 339

double[] num = {1.9, 2.9, 3.4, 3.5};
double max = num[0];
int    maxIndex = 0;
for (int i = 1 ; i < num.length ; i++)
{
   if (num[i] > max)
  {
    maxIndex = i
    max = num[i]; 
  }
}
System.out.println("Max is " + max);
System.out.println("Max index is + maxIndex);

Upvotes: 0

Related Questions