2

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));
2
  • hmm while I could provide an answer I'm pretty sure we have an XY problem here, can you edit the question and tell us the "X" :) ? Commented May 5, 2017 at 21:01
  • You are setting lowest to the lowest value initially and then setting it to the index value in the loop. You need to track the index and value separately. Commented May 5, 2017 at 21:02

4 Answers 4

3

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;  
}
Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

1

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

Comments

1

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.