0

I have the following simple Java statement:

public static void main(String[] args) 
{
    int[] grades = {102, 105, 98, 105};

    Sorts.selectionSort(grades);

    for (int grade : grades) {
   // {
        System.out.println(grade);
        try {
            System.out.print(grades[grade] + "     ");
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Error!");
        }
    }

And I'm getting the following output:

102
Error!
105
Error!
98
Error!
105
Error!

Why would the loop iterate to values that aren't in the array? I'm quite confused.

Thank you.

4

4 回答 4

1

int grade is the value of each element in the array, not the index.

If you want to get each element of int[] grades = {102, 105, 98, 105}; you should use a regular for loop like this:

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

This will work since the index of each element in the array ranges from 0 to 3.

Take a look at the enhanced for loop documentation.

于 2013-03-31T01:24:13.643 回答
1

It's throwing index out of bound errors, because the "grade" variable is already the value inside the array, not the index.

So it will print it out fine on the first System.out.println(), but then you're trying to do this inside the try/catch

grades[102]

And your array doesn't have that index. it's maximum index is 3 (-> 105).

于 2013-03-31T01:26:29.573 回答
0

The foreach loop iterates over the values of the array, not the indices.

Therefore, grade is 102.
You're trying to access the 103rd (0-based) element of a 4-item array.
That's not going to work

于 2013-03-31T01:24:09.203 回答
0

Your first print statement uses grade appropriately. The for loop iterates by assigning each value in the array to grade.

Your second print statement uses grade as an index into grades. This is wrong because the grade is a value in the array, not an index. Although the for loop you wrote is simpler than a for loop with an index, sometimes you do need to know the index so you might want to rewrite your for loop.

于 2013-03-31T01:29:54.867 回答