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.

1

4 Answers 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.

Sign up to request clarification or add additional context in comments.

Comments

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).

Comments

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

Comments

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.

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.