0

I have problem with my code below, here is the error:

Exception in thread "main" java.lang.NullPointerException at javaPractice.Difference.computeDifference(Difference.java:24) at javaPractice.diffSolution.main(diffSolution.java:18)

class Difference {

    private int[] elements;
    public int maximumDifference;

    public Difference(int[] a) {
        this.elements = a;
    }

    List<Integer> maximumDifferenceList;

    public void computeDifference() {
        for(int i = 0; i < elements.length; i++) {
            for(int j = 0; j < elements.length; j++) {
                if(i != j) {
                    maximumDifferenceList.add(Math.abs(elements[i] - elements[j]));
                }
            }
        }
        Collections.sort(maximumDifferenceList);
        maximumDifference = (int) Collections.max(maximumDifferenceList);
    }

}

public class diffSolution {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int[] a = new int[n];
        for (int i = 0; i < n; i++) {
            a[i] = sc.nextInt();
        }
        sc.close();

        Difference difference = new Difference(a);

        difference.computeDifference();

        System.out.print(difference.maximumDifference);
    }

}

I tried to print out elements array, it seems to have values but it does not evaluate the line below:

maximumDifferenceList.add(Math.abs(elements[i] - elements[j]));

Thank you in advanced!

Cham
  • 131
  • 1
  • 10

0 Answers0