在下面的代码中,我无法初始化BigInteger数组,因为在编译时抛出了NullPointerException:
public class Solution {
public static BigInteger[] arr;
public Solution(int n){
arr=new BigInteger[n];
for(BigInteger each:arr){
each=BigInteger.ZERO;
}
}
public static BigInteger maxlist(){
BigInteger max=arr[0];
for(BigInteger elem:arr)
if(elem.compareTo(max)>0)
max=elem;
return max;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int m = in.nextInt();
Solution s=new Solution(n);
for(int a0 = 0; a0 < m; a0++){
int a = in.nextInt();
int b = in.nextInt();
BigInteger k = in.nextBigInteger();
for(int i=a-1;i<=b-1;i++)
arr[i]=arr[i].add(k); //Error is thrown here
}
System.out.println(maxlist());
in.close();
}
}
错误:
Exception in thread "main" java.lang.NullPointerException
at Solution.main(Solution.java:29)
还有其他办法吗?
答案 0 :(得分:1)
您的阵列初始化不正确。
for(Type obj : arr) {
// in this context, obj does not refer to a part of the array.
// obj is an iteration variable, assigning values to obj will not affect the array.
}
您需要通过索引分配给数组:
for(int i = 0; i < arr.length; i++) {
arr[i] = BigInteger.ZERO;
}
你的完整构造函数应该是这样的:
public Solution(int n){
arr = new BigInteger[n];
for(int i = 0; i < n; i++){
arr[i] = BigInteger.ZERO;
}
}