package student;
import javax.swing.JOptionPane;
public class Student
{
private Name name;
String idNUM, course;
public Student(Name n, String idNum){
this.name = n;
this.idNUM = idNum;
}
public Name getName(){
return name;
}
public String getId(){
return idNUM;
}
}
package student;
public class StudentCourse
{
Student studInfo, studentInfo;
String studentCourses, studentCourse;
StudentCourse(String sc)
{
studentCourses = sc;
}
public String getCourses(){
return studentCourses;
}
}
package student;
public class StudentAccounts
{
private Student stud;
private String addedClass;
String courses;
public StudentAccounts (Student s, String course)
{
stud = s;
courses = course;
}
public Student getStudent()
{
return stud;
}
public void insertClass(String cla)
{
courses = cla;
}
public String getCourses()
{
return courses;
}
}
抱歉,发布了很多代码。但是问题就在这里。在下面的数据库类中。方法“ void addCourses(StudentCourse e)”。运行测试类时。输入课程名称后,它立即崩溃,不会像学生名称那样存储它。我对衔接编程有点新意。有人可以解释我所缺少的吗?
package student;
import java.util.ArrayList;
public class DataBase
{
ArrayList <StudentAccounts> list;
ArrayList <StudentCourse> courseList;
StudentAccounts sa ;
StudentCourse sc;
int index;
boolean found = false;
DataBase()
{
list = new ArrayList<> ();
}
ArrayList getList()
{
return list;
}
ArrayList getCourseList()
{
return courseList;
}
StudentCourse getCourse(){
return sc;
}
StudentAccounts getAccount()
{
return sa;
}
StudentAccounts delete (int d)
{
return list.remove(d);
}
boolean inList() //Looks in the ArrayList
{
return found;
}
boolean isEmpty()
{
return list.isEmpty();
}
int getIndex()
{
return index;
}
int getSize() // return the amount of strings in the Array
{
return list.size();
}
void add(StudentAccounts s)
{
list.add(s);
}
void addCourse(StudentCourse e)
{
courseList.addCourse(e);
}
void search(String key)
{
found = false;
int i = 0;
while (!found && i < list.size() )
{
StudentAccounts sl = list.get(i);
if(sl.getStudent().getId().equalsIgnoreCase(key))
{
sa =sl;
found = true;
index = i;
}
else
i++;
}
}
}
最佳答案
您尚未初始化courseList变量。您只初始化了构造函数数据库中的一个列表变量。添加课程时,addCourse()
方法将引发空指针异常。
在数据库构造函数中添加以下行:
courseList = new ArrayList<>();
另外,路线list.addCourse(e)行应该是编译错误(对我来说如此愚蠢)。 courseList是ArrayList类型的对象。 ArrayList类没有名为
addCourse(Studentcourse e)
的方法。它仅具有方法add()
,该方法将根据您的情况采用StudentCourse类型的对象。因此,您将看到一个找不到符号错误。将该行更改为:
courseList.add(e);