0

I am trying to create a custom array and want to add data by indexing using k (int). I don't know why it's giving me a null pointer exception.

public class FourElements_Sum_GivenVal {

    int sum,first,second;

    public static void findFourElements(int arr[],int n,int x) {

        int size=((n)*(n-1));
        FourElements_Sum_GivenVal aux[] =new FourElements_Sum_GivenVal[size/2];
        int k=0;
        //System.out.println((n*n-1)/2);

        for(int i=0;i<n-1;i++) {
            for(int j=i+1;j<n;j++) {
                aux[k].sum=arr[i]+arr[j];
                aux[k].first=i;
                aux[k].second=j;
                k++;

            }
        }
        public static void main(String[] args) {
        // TODO Auto-generated method stub

          int arr[]= {1,2,3};
          int x=23;
          findFourElements(arr,arr.length,x);
    }   
}
gunr2171
  • 16,104
  • 25
  • 61
  • 88
  • Please post the stacktrace. – m0skit0 Jun 20 '18 at 19:22
  • 2
    Because `FourElements_Sum_GivenVal aux[] =new FourElements_Sum_GivenVal[size/2];` creates an array with space for half of the `size` elements, but it does **not** instantiate any elements. Thus, when you say `aux[k].sum=arr[i]+arr[j];` `aux[k]` is `null`. Put a `aux[k] = new FourElements_Sum_GivenVal();` before that line. – Elliott Frisch Jun 20 '18 at 19:24
  • *(arr,arr.length,x)*??? You shouldn't do this anymore. When you pass an array to the method, **that** method should take care of `arr.length` – zlakad Jun 20 '18 at 19:25
  • Please look at the duplicate question and its answers in detail, because you will run into NPE's *very* often if you continue on in your coding education, and you will need to fully understand the process used to debug most of these. – Hovercraft Full Of Eels Jun 20 '18 at 19:29

0 Answers0