我编写了一个代码,用于在排序后保留索引的记录,但它显示我的空指针异常。我读了同一主题的其他线程,但仍然无法找到。
import java.io.*;
import java.util.*;
public class Solution {
class Order{
public int index;
public int sum;
public void setIndex(int index){
this.index = index;
}
public void setSum(int sum){
this.sum = sum;
}
public int getSum(){
return this.sum;
}
public int getIndex(){
return this.index;
}
}
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
Order array[] = new Order[N];
int index = 0;
int sum = 0;
while(index<N){
int input1 = sc.nextInt();
int input2 = sc.nextInt();
//line 32
array[index].setIndex(index);
array[index].setSum(input1+input2);
index++;
}
ArrayList<Order> list = new ArrayList<Order>(Arrays.asList(array));
Collections.sort(list, new Comparator<Order>(){
@Override
public int compare(Order o1, Order o2){
return(Integer.compare(o1.getSum(), o2.getSum()));
}
});
System.out.println(list);
}
}
错误是这样的:
Exception in thread "main" java.lang.NullPointerException
at Solution.main(Solution.java:32)
我正在传递i,仍为空指针为什么?
答案 0 :(得分:0)
使用Order array [] = new Order [N];初始化数组,但数组中充满了null对象。您需要使用新订单初始化每个元素,然后使用setter