我的代码有问题,这是错误:
线程中的异常" 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);
}
}
我试图打印出元素数组,它似乎有值,但它没有评估下面的行:
maximumDifferenceList.add(Math.abs(elements [i] - elements [j]));
先谢谢你了!