【问题标题】:cant fill array java无法填充数组java
【发布时间】:2011-09-22 15:44:41
【问题描述】:

我有一个公共整数数组,我想在数组中存储 1 或 2,但我收到错误 NullPointerException 我在做什么

    public int[] which;
    public int gotIt;

public void Check()
{


    int cont = 0;

   System.out.println(intento[0]);

        for(int j = 0;j <= spaces;++j)
        {
             if(tries[0] == words[numRandom][j])
            {
                which[gotIt] = j;//im getting the error here
                gotIt++;
            }
            else
            {
                 cont++;
            }
       }
        if(Contador == espacios+1)
        {
            Errors++;
            System.out.println("There was an error");
        }

        repaint();
}

错误是在我填充被调用的变量时,我不知道为什么会这样,非常感谢

【问题讨论】:

    标签: java arrays nullpointerexception


    【解决方案1】:

    您需要先分配数组,然后才能访问其元素:

    public int[] which = new int[n];
    

    其中n 是所需的数组大小。

    如果您事先不知道数组的大小,您可以保留变量声明原样,稍后再进行分配(但在您尝试使用数组之前):

    which = new int[n];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-05
      • 2015-02-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-04
      • 1970-01-01
      • 2020-10-22
      相关资源
      最近更新 更多