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();
}