如何在属于类的对象的数组的for循环中输入人员名称的字符串,然后输入学生id的数字


import java.util.Scanner;
class Student {
public int id;
public String name;
Student(int id, String name) {
this.id = id;
this.name = name;
}
}

第一个for循环是我遇到问题的地方,我试图为3个学生输入一个后面跟着id的名称,但它一直抛出一个空指针异常

错误显示如下:

javac-classpath。:/run_dir/junit-4.12.jar:/run_dir/hamcrest-core-1.3.jar:/run-dir/json-simple-1.1.1.jar-d。Main.java

java-classpath。:/run_dir/junit-4.12.jar:/run_dir/hamcrest-core-1.3.jar:/run-dir/json-simple-1.1.1.jar

Main输入学生1的名字:John线程中的异常";主";Main.Main处的java.lang.NullPointerException(Main.java:28(退出状态1

public class Main {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
Student children[] = new Student[3];

for (int i = 0; i < children.length; i++) {
System.out.print("Enter the name for student " + (i + 1) + ": ");
children[i].name = keyboard.nextLine();
System.out.print("Enter the id for student " + (i + 1) + ": ");
children[i].id = keyboard.nextInt();
}
// Display the name and the id for the 3 students.
for (int i = 0; i < children.length; i++) {
System.out.println("The first student is " + children[i].name + 
" and their student id is " + children[i].id);
}
keyboard.close();
}

由于Student数组为空,您将收到NullPointerException错误。Student children[] = new Student[3];只是创建了一个新的数组,大小为3,它将容纳Student对象。在循环中,在尝试为数组中的项赋值之前,需要添加一个新的Student。

children[i] = new Student(params);

您还可以创建变量来保存输入值,然后创建Student实例并在每次迭代结束时添加它。

import java.util.Scanner;
class Student {
public int id;
public String name;
Student(int id, String name) {
this.id = id;
this.name = name;
}
}
public class Main {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
Student children[] = new Student[3];
for (int i = 0; i < children.length; i++) {
children[i] = new Student(0, ""); // We have to initialize each student
System.out.print("Enter the name for student " + (i + 1) + ": ");
children[i].name = keyboard.nextLine();
System.out.print("Enter the id for student " + (i + 1) + ": ");
children[i].id = keyboard.nextInt();
keyboard.nextLine(); // We have to read the new line (n)
}
// Display the name and the id for the 3 students.
for (int i = 0; i < children.length; i++) {
System.out.println("The student number " + (i+1) + " is " + children[i].name + " and his student id is " + children[i].id);
}
keyboard.close();
}
}

最新更新