我的阵列是空的吗?如果是这样,为什么?错误“java.lang.NullPointerException”

时间:2016-01-24 10:33:43

标签: java arraylist

我是编程新手。请解释,以便初学者能够理解。

我正在尝试建立彩票。 首先,我用所需的数字填充数组。然后画一个数字。该号码将从彩票中删除并返回主页,并在控制台上打印。重复此过程,直到绘制完所有数字。

这就是我想要的。但我收到错误“java.lang.NullPointerException”。

我的阵列是空的吗?如果是这样,为什么?

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());
    }
  }
}

2 个答案:

答案 0 :(得分:1)

您正在初始化<td>构造函数中的本地var contact = []; //set up array var i = 0; function displayContact() { //create function to display object contents console.log(this.name); console.log(this.telephone); console.log(this.email); } //create two empty objects in array for (i = 0; i < 2; i = i + 1) { contact[i] = {}; } //Create properties (with some test data) contact[0].name = "Mr Blue"; contact[0].telephone = "08870 7980 11291"; contact[0].email = "Mister_Blue@somewhere.se"; contact[1].name = "Mr Blue"; contact[1].telephone = "07880 7880 11281"; contact[1].email = "Mister_Blue@somewhere.se"; //create method for each object for (i = 0; i < 2; i = i + 1) { contact[i].logDetails = displayContact; } //test the method for (i = 0; i < 2; i = i + 1) { contact[i].logDetails(); } ,而不是初始化您的实例变量。这就是你的实例变量保持为空的原因。

变化

ArrayList

Tombola

答案 1 :(得分:0)

尝试在lottery中初始化ArrayList constructor,如下所示:

    public Tombola(int n){
    this.numbers = n;
     lottery = new ArrayList<Integer>();