0
import java.io.*;

import java.util.*;

class Mean { 

    int n, a[] = new int[n] , sum = 0, avg;

    public int getMean() { 

        Scanner in = new Scanner(System.in);
        n = in.nextInt();

        for (int i = 1; i <= n; i++) { 
            a[i] = in.nextInt();
            sum = sum + a[i];
        }

        avg = sum / n;
        return avg;
    }

    public void displayMean() {
        System.out.println(avg);
    }

}


public class TestClass {

    public static void main(String[] args) { 
        Mean obj = new Mean();
        obj.getMean();

        obj.displayMean();

    }
}

Testcase 1 : 5

1 3 4 5 6

expected output: 3

deHaar
  • 17,687
  • 10
  • 38
  • 51
mundam
  • 1
  • 1
  • Possible duplicate of [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) – Progman Dec 21 '18 at 11:30

1 Answers1

1

You must allocate the array a after you read the value of n. In your code, n is initialized to 0 and the array a has zero length. Even if you change the value of n later, the length of a does not change.

The definition line becomes:

int n, a[] , sum = 0, avg;

And you allocate like this:

n = in.nextInt();
a = new int[n];
AhmadWabbi
  • 2,253
  • 1
  • 20
  • 35