我尝试输出get方法时出现NullPointerException

时间:2016-06-09 07:19:17

标签: java arraylist random

我有一个问题类对象的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;}

1 个答案:

答案 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