Я получаю NullPointerException
, когда использую этот метод. Кто-то сказал мне, что это потому, что student.getId ()
возвращает ноль. Я пытался исправить это, но не могу понять. Ниже приведен лишь фрагмент кода, только метод и класс Student
.
edit: Я добавил часть, в которой был создан массив.
Student[] students ;
public Student[] enterStudents(){
Scanner input = new Scanner(System.in);
System.out.println("Enter number of students");
int numOfStudents = input.nextInt();
Student[] students = new Student[numOfStudents];
int i;
for(i = 0; i <= numOfStudents - 1; i++){
System.out.println("Enter student's ID: ");
int id = input.nextInt();
System.out.println("Enter student's first name: ");
String first = input.next();
System.out.println("Enter student's last name: ");
String last = input.next();
System.out.println("Enter student's class: ");
String stuClass = input.next();
Student x = new Student(id,first,last,stuClass);
students[i] = x;
}
return students;
}
public void retrieveStuId(){
Scanner input = new Scanner(System.in);
System.out.println("Enter student id");
int searchID = input.nextInt();
int i;
for(i = 0; i < students.length; i++){
Student student = students[i];
int search = student.getId();
if (search == searchID) {
System.out.println(student.toString());
}
}
}
class Student{
private int studentID;
private String firstName;
private String lastName;
private String stuClass;
public Student(){
}
public Student(int id, String first, String last, String c ){
studentID = id;
firstName = first;
lastName = last;
stuClass = c;
}
public void setID (int id){
studentID = id;
}
public void setStuClass (String c){
stuClass = c;
}
public void setFirst(String first){
firstName = first;
}
public void setLast(String last){
lastName = last;
}
public String getFirst(){
return firstName;
}
public String getLast(){
return lastName;
}
public int getId(){
return studentID;
}
public String getStuClass(){
return stuClass;
}
public String toString(){
return "Student ID: " + studentID + " --- " + "Student Name: " + firstName + " " + lastName + " --- " + "Class:" + stuClass;
}
}
Заранее благодарим за любую помощь.