简单的java问题,但是运行时就出错了。该如何解决
import java.util.Scanner;
public class NewClass {
public static void main(String args[]) {
NewClass application = new NewClass();
System.out.println("How many students do you want to input?");
Scanner str = new Scanner(System.in);
int n = str.nextInt();
Student[] student = new Student[n];
application.init(student);
application.sort(student);
application.output(student);
}
public class Student {
public String number;
public String name;
public int scores;
public Student(String number, String name, int scores) {
this.number = number;
this.name = name;
this.scores = scores;
}
}
public void init(Student[] student) {
System.out.println("Please input " + student.length + " students' number,name and scores");
Scanner string = new Scanner(System.in);
for (int i = 0; i < student.length; i++) {
student[i].number = string.nextLine();
student[i].name = string.nextLine();
student[i].scores = string.nextInt();
}
}
public void sort(Student[] student) {
Student temp = new Student("3", "enen", 3);
for (int i = 0; i < student.length - 1; i++) {
for (int j = 1; j < student.length; j++) {
if (student[i].scores < student[j].scores) {
temp = student[i];
student[i] = student[j];
student[j] = temp;
}
}
}
}
public void output(Student[] student) {
for (int i = 0; i < student.length; i++) {
System.out.println(student[i].name);
}
}
}
------解决方案--------------------
Java code
import java.util.Scanner;
public class NewClass {
public static void main(String args[]) {
NewClass application = new NewClass();
System.out.println("How many students do you want to input?");
Scanner str = new Scanner(System.in);
int n = str.nextInt();
Student[] student = new Student[n]; // 只是初始化了数组,说明数组能放多少个Student对象,里面的每个Student对象还没有生成
application.init(student);
application.sort(student);
application.output(student);
}
public class Student {
public String number;
public String name;
public int scores;
public Student(String number, String name, int scores) {
this.number = number;
this.name = name;
this.scores = scores;
}
}
public void init(Student[] student) {
System.out.println("Input format: number, name, scores");
System.out.println("Please input " + student.length + " students' number,name and scores");
Scanner string = new Scanner(System.in);
for (int i = 0; i < student.length; i++) {
String str = string.nextLine();
String[] fields = str.split(",\\s*");
System.out.println(fields);
Student s = new Student(fields[0], fields[1], Integer.parseInt(fields[2])); // 生成Student对象
student[i] = s;
}
}
public void sort(Student