Fouroh3
Fouroh3

Reputation: 542

Why is this for-loop giving me a null pointer exception?

This code is giving me a NullPointerException. Its purpose is to loop through an ArrayList and return any Records that match the parameter, age.

private String searchAge(int age) {

    for(int i = 0; i < list.size(); i++) {    //<--- ERROR ON THIS LINE
        if(list.get(i).getAge() == age) {
            System.out.println(list.get(i));
            return list.get(i).toString();
        }
    }

    return "No Records Found!";
}

My Constructor:

public Frame() {
    Objects a = new Objects();
    list = a.getList();
}

And The Other Class:

package objects;

import java.util.ArrayList;

public class Objects {


    public ArrayList<Student> list;

    public static void main(String[] args) {
        Objects a = new Objects();
        a.addStudents();
        Frame f = new Frame();
        f.setVisible(true);

    }

    public ArrayList<Student> getList() {
        return list;
    }

    public void addStudents() {
        list = new ArrayList<>();
        list.add(new Student("Joe Wilson", 16, 11));
        list.add(new Student("Bill Johnson", 16, 10));
        list.add(new Student("Joe Jonson", 15, 9));
        list.add(new Student("William Smith", 17, 12));
        list.add(new Student("Dan Smith", 16, 11));

    }

}

Upvotes: 0

Views: 2648

Answers (2)

Alexis C.
Alexis C.

Reputation: 93872

The problem is your Frame constructor :

public Frame() {
    Objects a = new Objects(); //<-- new object of type Objects
    list = a.getList(); //<-- call getList but list is null
}

Two solutions are possible :


Keep your current constructor :

public Frame() {
        Objects a = new Objects(); 
        a.addStudents(); // <-- calling this method will initialize your list
        list = a.getList();
}


Consider pass the Objects object (btw you should use another name) as argument :

public Frame(Objects a) {
    list = a.getList(); //<-- call getList but list is null
}

And then in your main :

Frame f = new Frame(a);

Upvotes: 2

Elliott Frisch
Elliott Frisch

Reputation: 201467

Change

for(int i = 0; i < list.size(); i++) {

to

for(int i = 0; i < (list != null) ? list.size() : 0; i++) {

Or, if you do not like the ternary operator (it is rather ugly). Add these lines before your for loop

if (list == null || list.size() < 1) {
  return "No Records Found!";
}

Upvotes: 2

Related Questions