我有一个问题类对象的ArrayList,我需要输出随机选择的问题。 everithing似乎没问题,但是当我运行它时,给我一个java lang nullpointerException
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;}
答案 0 :(得分:2)
将您的代码更改为
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
属于Random
类型,但您尚未对其进行初始化。如您所知,所有非原始实例变量都使用null
初始化为默认值,因此这意味着您正在对null
执行操作,结果为nullpointerexception