Java 尝试输出get方法时出现NullPointerException
我有一个问题类对象的数组列表,我需要输出随机选择的问题。所有这些看起来都没问题,但当我运行它时,给了我一个JavaLangNullPointerExceptionJava 尝试输出get方法时出现NullPointerException,java,arraylist,random,Java,Arraylist,Random,我有一个问题类对象的数组列表,我需要输出随机选择的问题。所有这些看起来都没问题,但当我运行它时,给了我一个JavaLangNullPointerException public class GameBean implements Serializable { private Random random; private String question; private String answer; //above are the attributes 方法 public Question
public class GameBean implements Serializable {
private Random random;
private String question;
private String answer;
//above are the attributes
方法
public Question getQuestion() {
int index = random.nextInt(questionList.size());
Question q = questionList.get(index);
return q;}
将代码更改为
public Question getQuestion() {
random=new random();// this line added
int index = random.nextInt(questionList.size());
Question q = questionList.get(index);
return q;}
当你做了
private Random
您刚刚声明random
属于random
类型,但尚未初始化它。正如您所知,所有非基本实例变量都是以null
作为默认值初始化的,因此这意味着您正在null
上执行操作,结果是nullpointerexception
您确定已初始化random
?