kay
kay

Reputation: 11

Why is this piece of code giving index out of bound error?

public class ForEach {
    Scanner sc = new Scanner(System.in);
    int[] arr = new int[5];

    void setMarks()
    {
        for(int j : arr)
        {
            arr[j] = sc.nextInt();
        }
    }

    void getMarks()
    {
        for(int k : arr)
        {
            System.out.println(arr[k]);
        }
    }
    
    public static void main(String[] args)
    {
        System.out.println("Enter the marks of 5 subjects : ");
        ForEach fe = new ForEach();
        fe.setMarks();
        System.out.println(fe.arr.length);
        fe.getMarks();
    }
}

I am just trying to input marks of 5 subjects and display it on the screen. I got this error

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5
    at ForEach.getMarks(ForEach.java:17)
    at ForEach.main(ForEach.java:27)

Upvotes: 1

Views: 122

Answers (3)

Oleg Cherednik
Oleg Cherednik

Reputation: 18255

You use for loop incorrectly. It has two ways to use.

First way

int[] arr = new arr[10];

for(int i = 0; i < arr.length; i++)
    arr[i] = 1;

This will set 1 to all elements.

Just why 99% of all usage of for loop just iterates over an array, there is the second way.

int[] arr = { 1,2,3 };

for(int a : arr)
    System.out.print(a);    // print 123

// i.e. the same

for(int i = 0; i < arr.length; i++)
    System.out.print(arr[i]);

Note, that this way you can use only to read element from array from first to last elements.

So, you should change your code to:

public class ForEach {
    Scanner sc = new Scanner(System.in);
    int[] arr = new int[5];

    void setMarks() {
        for(int i = 0; i < arr.length; i++)
            arr[i] = sc.nextInt();
    }

    void getMarks() {
        for(int a : arr)
            System.out.println(a);
    }
    
    public static void main(String[] args)
    {
        System.out.println("Enter the marks of 5 subjects : ");
        ForEach fe = new ForEach();
        fe.setMarks();
        System.out.println(fe.arr.length);
        fe.getMarks();
    }
}

Upvotes: 0

Dhanraj
Dhanraj

Reputation: 139

Also, your setMarks method would set data to only the 0th index. Because "j" points to the value and not to the index. you might have to refactor you setMarks method like the below -

int pos = 0;

for(int j:arr){

arr[pos] = sc.nextInt();

pos++;

}

or better use the normal for loop.

Upvotes: 0

John Glenn
John Glenn

Reputation: 1629

Your getMarks function is reading an integer out of the array and then trying to go to the position in the array indicated by that integer. If your array has one element and is { 100 }, the code inside your loop will try to print the 100th (really 101st because the index starts at 0) element in your array.

The following code should fix the issue:

void getMarks()
{
    for(int k : arr) {
        System.out.println(k);
    }
}

Upvotes: 2

Related Questions