[英]Why is this for-loop giving me a null pointer exception?
This code is giving me a NullPointerException
. 这段代码给了我
NullPointerException
。 Its purpose is to loop through an ArrayList
and return any Records that match the parameter, age. 它的目的是循环遍历
ArrayList
并返回与参数age匹配的所有Records。
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));
}
}
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
在for循环之前添加这些行
if (list == null || list.size() < 1) {
return "No Records Found!";
}
The problem is your Frame constructor : 问题是您的Frame构造函数:
public Frame() {
Objects a = new Objects(); //<-- new object of type Objects
list = a.getList(); //<-- call getList but list is null
}
Two solutions are possible : 两种解决方案是可能的:
public Frame() { Objects a = new Objects(); a.addStudents(); // <-- calling this method will initialize your list list = a.getList(); }
Objects
object (btw you should use another name) as argument :
Objects
对象(应该使用另一个名称)作为参数:
public Frame(Objects a) { list = a.getList(); //<-- call getList but list is null }
And then in your main : 然后在您的主要:
Frame f = new Frame(a);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.