0
int[] myArray = new int[] {1,2,3,4,5,6,7,8,9,10};        

for(int number : myArray) {
    System.out.println(myArray[number]);
}

and this is the output:

2
3
4
5
6
7
8
9
10

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10
    at javaPractice.selfAssignArrays.main(selfAssignArrays.java:10)

what's wrong with it?

1
  • What do you think is right with it? What does myArray[number] do? What is each value of number at each iteration? What is the base index of an array? Commented Apr 8, 2014 at 1:15

3 Answers 3

1

You want to do this:

for (int number : myArray) {
    System.out.println(number);
}

This is equivalent to this:

for (int i=0; i<myArray.length; i++)  {
    int number = myArray[i];
    System.out.println(number);
}
Sign up to request clarification or add additional context in comments.

2 Comments

The "" + isn't necessary; System.out.println(number); will do the same thing.
Yes you are right. Been doing too much Android where setText() is a strict string type. I will edit my answer.
0

Because the enhanced for loop sets number to each value in myArray, not to each index. (Note that the first element being printed is 2, which is the element at index 1.) Your enhanced for loop is more or less equivalent to:

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

What you want is:

for (int number : myArray) {
    System.out.println(number);
}

Comments

0

For each iteration, you get the number from array, and you take the number as the index. that's why ArrayIndexOutOfBoundsException happened.

System.out.println(myArray[1]); System.out.println(myArray[2]); System.out.println(myArray[3]); System.out.println(myArray[4]); System.out.println(myArray[5]); System.out.println(myArray[6]); System.out.println(myArray[7]); System.out.println(myArray[8]); System.out.println(myArray[9]); System.out.println(myArray[10]);

Get it? You should start from System.out.println(myArray[0]); and end at System.out.println(myArray[9]); Alternatively, just output the number as System.out.println(number);

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.