-1

I'm relatively new to Java and I'm having a problem with a foreach loop in a method I'm writing. I keep getting an astronomical index out-of-bounds error but I have no idea where it's coming from.

Here's my code.

public static int smallestInt(int[] arr)
{
    int minVal = Integer.MAX_VALUE;
    
    
    for (int value : arr)
    {
        if (arr[value] < minVal)
        {
            minVal = arr[value];
        }
    }
    if (arr.length == 0)
    {
        return Integer.MIN_VALUE;
    }
    
    return minVal;

}

The error thrown states: Index 88 out of bounds for length 6

Any help will be appreciated, as I have been stuck on this for quite a while

2 Answers2

1

A for-each loop access an array value with a hidden index. This

if (arr[value] < minVal)
{
    minVal = arr[value];
}

Should be

if (value < minVal)
{
    minVal = value;
}

or

minVal = Math.min(minVal, value);
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
1

Try applying this to your array

    public static int smallestInt(int[] arr)
{
    int minVal = arr[0];
    
    
    for (int value : arr)
    {
        if (arr[value] < minVal)
        {
            minVal = arr[value];
        }
    }
    
    return minVal;
}

the array value will never be less than the Integer.MAX_VALUE because you are setting the minVal variable to the highest number possible that can be stored as a int which is 2147483647