ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3

We Are Going To Discuss About ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3. So lets Start this Java Article.

ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3

  1. ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3

    because array index start at 0
    public static void main(String[] args) { Scanner input = new Scanner(System.in); int n = 3; int[] numbers = new int[n]; float total = 0; for (int i = 0; i <= 2; i++) { int row=i+1;

  2. ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3

    because array index start at 0
    public static void main(String[] args) { Scanner input = new Scanner(System.in); int n = 3; int[] numbers = new int[n]; float total = 0; for (int i = 0; i <= 2; i++) { int row=i+1;

Solution 1

because array index start at 0

 public static void main(String[] args) {

Scanner input = new Scanner(System.in);
int n = 3;
int[] numbers = new int[n];
float total = 0;

for (int i = 0; i <= 2; i++) {
int row=i+1;
    System.out.println("Please type the number " + row + ":");
    numbers[i] = input.nextInt();

    total = total + numbers[i];

}

System.out.println("The average of the 3 number is: " + total / n);
}

Original Author AMA Of This Content

Solution 2

Indexes starts from 0. Your length is 3 and your counter variable (i) starts from 1.

You can use

for (int i = 0; i < 3; i++)

Original Author Semih Çavdar Of This Content

Solution 3

Try this, insert this inside your main method

Scanner input = new Scanner(System.in);

    int n = 3;
    int[] numbers = new int[n];
    float total = 0;


    for (int i = 0; i < 3; i++) {

        System.out.println("Please type the number " + (i + 1) + ":");
        numbers[i] = input.nextInt();

        total = total + numbers[i];

    }


    System.out.println("The average of the 3 number is: " + total / n);

Original Author Royeth Gomeseria Of This Content

Solution 4

If you’re facing error listed below

Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3

var arr = arrayOf("One","Two","Three")
 println(arr[3])

In this Array we just defined three values and index start from 0, So Index 3 doesn’t exist in array that’s why it’s giving this Exception

Try to print index value which includes in Array Such As

println(arr[1])

Original Author Rehan Khan Of This Content

Conclusion

So This is all About This Tutorial. Hope This Tutorial Helped You. Thank You.

Also Read,

Siddharth

I am an Information Technology Engineer. I have Completed my MCA And I have 4 Year Plus Experience, I am a web developer with knowledge of multiple back-end platforms Like PHP, Node.js, Python and frontend JavaScript frameworks Like Angular, React, and Vue.

Leave a Comment