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 =
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;
}
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;
}
You need to store lowest_seen and lowest_index. Right now you are comparing value < last_index
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;