Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/fsharp/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 尝试输出get方法时出现NullPointerException_Java_Arraylist_Random - Fatal编程技术网

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

Java 尝试输出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

我有一个问题类对象的数组列表,我需要输出随机选择的问题。所有这些看起来都没问题,但当我运行它时,给了我一个JavaLangNullPointerException

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