Makri
Makri

Reputation: 341

I get an exception when trying to find smallest value array

I am trying to find the smallest value in an array of integers, but when I do I get an arrayindexoutofbounds on a place which, as far as I know, there shouldn't be a counting of array-index, only a comparison of the index and a min-value. Part of code in question underneath:

    }
    System.out.println(sum);

    int minste=tall[0]; 
    for (int i : tall){ 
        if(tall[i]<tall[0]){ //This is where the exception is made. But why?
        minste=tall[i]; 
        }
    }
    System.out.println(minste);
    }
}

Upvotes: 0

Views: 87

Answers (3)

Maroun
Maroun

Reputation: 95948

i is already an element, just use it. No need to tall[i]:

if(i < minste) {

This loop means: "For each int in tall".

In order to better understand the enhanced loop, think about it this way:

for(int i = 0; i < tall.length; i++) {
   System.out.println(tall[i]); 
}

Will print the same thing as:

for(int i : tall) {
   System.out.println(i);
}

That's why it's recommended to use a meaningful name for the variable, instead of i, use item, so it'll be like "for each item in tall"...

Alternative solution to find the smallest value:

  1. Use Arrays#sort
  2. Return the first element in the array

Upvotes: 3

Dia
Dia

Reputation: 271

You are using for-each loop, but try to use i as a index. To work properly change your code to

int minste = tall[0]; 
for (int i : tall)
{ 
    if(i < minste)
    {
        minste = i; 
    }
}

or

int minste = tall[0]; 
for (int i = 0; i<tall.length; i++)
{ 
    if(tall[i] < minste)
    {
        minste = tall[i]; 
    }
}

Upvotes: 0

Rahul
Rahul

Reputation: 45060

When you're using the for-each loop, why use the indexes?

if(tall[i]<tall[0]){

tall[i] - gives the ArrayIndexOutOfBoundsException because i is an element in your array and not an index value. And that value i is definitely more than the length of your array.

All you need to do is thi

int minste = tall[0]; 
for (int i : tall) { 
    if(i < minste) { 
        minste = i; 
    }
}

Upvotes: 2

Related Questions