0

I am a newbie in programming. Please explain so that a beginner can understand.

I'm trying to build a lottery. First I fill the array with the desired number of numbers. Then draw a number. The number is removed from the lottery and returned to main where it is printed on the console. This is repeated until all the numbers are drawn.

This is what I want. But I get the error "java.lang.NullPointerException".

Is my array empty? And if so, why?

import java.util.*;

public class Tombola {

  private ArrayList<Integer> lottery;
  private int numbers;

  public Tombola(int n){

    this.numbers = n;   
    ArrayList<Integer> lottery = new ArrayList<Integer>();
    for(int i = 0; i < this.numbers; i++){
        this.lottery.add(i+1);  
    }
  }

  public int draw(){
    int drawnNumber = this.lottery.get((int) (Math.random() * numbers));
    for(int i = 0; i < numbers; i++){
        if(this.lottery.get(i) == drawnNumber){
            this.lottery.remove(i);
            break;
        }   
    }
    this.numbers--;
    return drawnNumber;
  }

  public static void main(String[] args) {

    int x = 10;
    Tombola jackpot = new Tombola(x);
    for(int i = 0; i < x; i++){
    System.out.println(jackpot.draw());
    }
  }
}
APC
  • 144,005
  • 19
  • 170
  • 281
GorAhl
  • 61
  • 7

2 Answers2

1

You are initializing a local ArrayList in your Tombola constructor instead of initializing your instance variable. That's the reason your instance variable remains null.

change

ArrayList<Integer> lottery = new ArrayList<Integer>();

to

lottery = new ArrayList<Integer>();
Eran
  • 387,369
  • 54
  • 702
  • 768
0

Try to initialize the ArrayList lottery in your constructor like this:

    public Tombola(int n){
    this.numbers = n;
     lottery = new ArrayList<Integer>();
Abdelhak
  • 8,299
  • 4
  • 22
  • 36