在Java中,比如我们新建一个Student类,我们可以通过它来new一个Student对象,但是当我们需要new多个Student对象时,往往需要借助数组或者其他数据结构(List、Queue)。
今天解决的是用数组存放对象时的空指针异常,新手很容易碰到,下面是解决办法
即在当我们在通过数组遍历对象时,一定要再对对象(students[i])进行一次赋值处理,因为Student[] students=new Student(n);只能够新建一个大小为n的Student数组对象,并不能实例化数组内每一个Student对象,所以一定要遍历数组并给每一个Student对象赋值(student[i]=new Student())。
package Sort;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;
public class Scholarship {
static int n; //学生人数
static Student[] students;
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
n=input.nextInt();
students=new Student[n]; //通过数组存放对象
for (int i = 0; i < n; i++) {
students[i]=new Student();//注意:一定要有这一句
students[i].id=i+1;
students[i].ch=input.nextInt();
students[i].math=input.nextInt();
students[i].eng=input.nextInt();
students[i].sum=students[i].getSum();
System.out.println("学生"+i+"的信息为 "+students[i].toString());
}
}
}
class Student implements Comparable<Student>{
int id;
int ch,math,eng;
int sum;
public Student(){
this.id = 0;
this.ch = 0;
this.math = 0;
this.eng = 0;
this.sum=0;
}
public Student(int id, int ch, int math, int eng) {
this.id = id;
this.ch = ch;
this.math = math;
this.eng = eng;
this.sum=ch+math+eng;
}
}