April 2, 2012

for each loop exception

Question by oneofthelions

I get an exception in my second print line.

int num[] = {50,20,45,82,25,63};
System.out.print("Given number : ");
for(int d:num){
System.out.print("  " + num[d]);
}

The console output is

Given number : Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 50

Why doesn’t d take all the array elements but only 50?

Answer by Starx

In the for(int d:num) loop every item is represented by d not num[d]

So, here is how it should be done.

for(int d:num){
    System.out.print("  " + d);
}

A simple dry run will show you where you went wrong.

For the first loop your statement will come down to num[50] which is not available anywhere, so you get the exception.


However, if your attempt was to use indexing, then a simple trick below will do the trick

int index = 0;
for(int d:num){
    System.out.print("  " + num[index++]);
}

But I honestly believe, this is not the correct solution to the problem.

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!