Mark Codd
Mark Codd

Reputation: 31

Finding the index number of the lowest value in an array

I have to return the index number of the lowest value in an array of 12 numbers. I keep getting 12 as the result every time I run it. Here is my code:

minRain = leastRain(months);

public static int leastRain (double[] mon4){
    int lowest = (int) mon4[0];

    for (int index=1; index<mon4.length; index++){
        if (mon4[index]<lowest)
            lowest = index;
    }
    return lowest;  
}

System.out.println("The month with the lowest amount of rain is: " + (minRain + 1));

Upvotes: 2

Views: 130

Answers (4)

Vasu
Vasu

Reputation: 22452

You are assigning array value to the lowest, so change it as shown below:

public static int leastRain (double[] mon4){
    int lowestIndex = 0;//set index as 0 instead of array value
    int lowestValue = mon4[0];
    for (int index=1; index<mon4.length; index++){
        if (mon4[index] < lowestValue)
            lowestIndex = index;
    }
    return lowestIndex;  
}

Upvotes: 3

Wasi Ahmad
Wasi Ahmad

Reputation: 37761

What is the meaning of this statement?

int lowest = (int) mon4[0];

You are saving the first value of the array as the lowest one and then later comparing with array values. You are actually comparing index with array values.

if (mon4[index]<lowest) // comparing lowest as an array value
    lowest = index;     // saving the index as the lowest value

You should do something like this.

 if (mon4[index]<mon4[lowest]) // comparing value of 'index' 'vs. 'lowest' index location
     lowest = index;

Upvotes: 1

Manish Kumar Sharma
Manish Kumar Sharma

Reputation: 13442

It is a silly mistake you made - you assigned index to your variable instead of an array value. Do this:

public static int leastRain (double[] mon4){
    int lowest = 0;

    for (int index=1; index<mon4.length; index++){
        if (mon4[index]<mon4[lowest])
            lowest = index;
    }
    return lowest;  
}

Upvotes: 3

Tezra
Tezra

Reputation: 8833

You need to store lowest_seen and lowest_index. Right now you are comparing value < last_index

Upvotes: 1

Related Questions