0

This is my code and Iam getting ArrayIndexoutofBoundsException and cant able to find where

import java.util.Scanner;
public class Main
{
    public static void main(String[] args) {
        int sum=0,sumtotal;
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter x");
        int x = sc.nextInt();
        sumtotal = (x+1)*(x+2)/2;
        System.out.println("Enter the size of array");
        int n = sc.nextInt();
        int a[] = new int[n];
        System.out.println("Enter values of array");
        for(int i = 0;i<n;i++){
            a[i] = sc.nextInt();
        }
        for(int i = 0;i<=a.length;i++)
        sum = sum+a[i];
        int miss = sumtotal-sum;
        System.out.println(miss);
    }
}

I put size of array 5 values are 1,2,4,5,6 and value of x is 5

  • 1
    `i<=a.length` must be `i < a.length` – Thiyagu Jan 27 '21 at 13:27
  • 2
    Does this answer your question? [What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?](https://stackoverflow.com/questions/5554734/what-causes-a-java-lang-arrayindexoutofboundsexception-and-how-do-i-prevent-it) –  Jan 27 '21 at 13:40

1 Answers1

0

You need to change the for loop from

 for(int i = 0;i<=a.length;i++)

to

 for(int i = 0;i<a.length;i++)

because the range of i is from 0 to 5 and your array a have index from 0 to 4 only.

Joby Wilson Mathews
  • 10,528
  • 6
  • 54
  • 53
  • [Should you answer questions where the cause of the problem is a typo?](https://meta.stackoverflow.com/questions/366135/should-you-answer-questions-where-the-cause-of-the-problem-is-a-typo) – Lino Jan 27 '21 at 13:35