JSox JSox - 7 months ago 9
Java Question

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.

Answer

Wow you still got some learning ahead of you, lad.

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