import java.util.Scanner;
class Student {
public int id;
public String name;
Student(int id, String name) {
this.id = id;
this.name = name;
}
}
The first for loop is where I am having trouble, I am trying to enter a name followed by an id for 3 students but it keeps throwing a null pointer exception
The error is displayed as follows:
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 Enter the name for student 1: John Exception in thread "main" java.lang.NullPointerException at Main.main(Main.java:28) exit status 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();
}
You're getting a NullPointerException error because your Student array is empty. Student children[] = new Student[3];
Just creates a new array of size three which will hold Student objects. In the loop before you try assigning values to items in the array, you need to add a new Student.
children[i] = new Student(params);
You could also create variables to hold the input values and then create the Student instance and add it at the end of each iteration.
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();
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.