-2

I am trying to make a student registration interface with several classes, provided in the requirement. In doing so, the linkedlist in my CourseFactory class is showing a null pointer.

public class Course {

private String id;
private String title;
private int credit;
private int tuitionPerCredit;

public void setId(String id){
    this.id=id;
}

public String getId(){
    return this.id;
}

public void setTitle(String title){
    this.title=title;
}

public String getTitle(){
    return this.title;
}

public void setCredit(int credit){
    this.credit=credit;
}

public int getCredit(){
    return this.credit;
}

public void setTuitionPerCredit(int tuitionPerCredit){
    this.tuitionPerCredit=tuitionPerCredit;
}

public int getTuitionPerCredit(){
    return tuitionPerCredit;
}

public int getSubTotal(){
    return this.credit*this.tuitionPerCredit;
}
}

And CourseFactory class

import java.util.LinkedList;

import static android.R.attr.id;

public class CourseFactory {

    LinkedList<Course> cList;

public void CourseFactory(){
    Course course = new Course();
    course.setId("CSE327");
    course.setTitle("SOFT ENG");
    course.setCredit(3);
    course.setTuitionPerCredit(1500);
    cList.add(course);

    Course course1 = new Course();
    course1.setId("CSE115");
    course1.setTitle("INTRO C");
    course1.setCredit(3);
    course1.setTuitionPerCredit(1500);
    cList.add(course1);

    Course course2 = new Course();
    course2.setId("CSE215");
    course2.setTitle("INTRO JAVA");
    course2.setCredit(3);
    course2.setTuitionPerCredit(1500);
    cList.add(course2);

    Course course3 = new Course();
    course3.setId("CSE225");
    course3.setTitle("DATA STRUCT");
    course3.setCredit(3);
    course3.setTuitionPerCredit(1500);
    cList.add(course3);

    Course course4 = new Course();
    course4.setId("CSE373");
    course4.setTitle("ALGOR.");
    course4.setCredit(3);
    course4.setTuitionPerCredit(1500);
    cList.add(course4);
}


public Course getCourse(String id){
    int temp = 0;
    for(int i=0;i<cList.size();i++) {
        if (cList.get(i).getId().equals(id)) {
                temp=i;
            break;
            }
        }
    return cList.get(temp);
    }
  }

The error is on the line "if (cList.get(i).getId().equals(id))

Rahul Kumar
  • 5,120
  • 5
  • 33
  • 44

2 Answers2

3

You have to initialize LinkedList. Or else it will get null-pointer exception.

LinkedList<Course> cList=new LinkedList<Course>();
Rahul Kumar
  • 5,120
  • 5
  • 33
  • 44
0

You need to initialize cList before use

LinkedList<Course> cList=new LinkedList<Course>();

or better, initialize into CourseFactory's constructor

public void CourseFactory(){

      cList=new LinkedList<Course>();

      Course course = new Course();
      ...
      ...
}

diamond operator is supported in -source 7 or higher

LinkedList<Course> cList=new LinkedList<>();
Abhishek Aryan
  • 19,936
  • 8
  • 46
  • 65