-1

I have an ArrayList of Question Class objects and I need to output the random selected question. everithing seems OK but when I run it, gives me a java lang nullpointerException

public class GameBean implements Serializable {

private Random random;
private String question; 
private String answer;
//above are the attributes

METHOD

public Question getQuestion() {
int index = random.nextInt(questionList.size());
Question q = questionList.get(index);

return q;}
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Exit
  • 73
  • 9

1 Answers1

2

change your code to

public Question getQuestion() {
random=new random();// this line added
int index = random.nextInt(questionList.size());
Question q = questionList.get(index);

return q;}

when you did private Random random; you have just declared that random is of Random type but you have not initialized it. As you know all non primitive instance variables are initialized with null as default value, so this mean you are doing operations on null which results nullpointerexception

SpringLearner
  • 13,738
  • 20
  • 78
  • 116