【问题标题】:Unknown Null Pointer Exception when adding an element to an arraylist将元素添加到数组列表时出现未知的空指针异常
【发布时间】:2014-11-16 06:33:00
【问题描述】:

我要做的是在每次调用方法时向 ArrayList 添加一个元素。

public class Dice
{
private static int x3;
private static ArrayList<Integer> totals;

public Dice()
{
totals = new ArrayList<Integer>();
}

public static void Roll()
{
int x1 = (int)(Math.random()*6)+1;
int x2 = (int)(Math.random()*6)+1;
x3 = x1 + x2;
totals.add(x3);
}
}

每次调用 Roll() 方法时,我都会收到“totals.add(x3);”的空指针错误

有什么想法吗?

【问题讨论】:

  • 在您发布的代码中,Roll() 不在 Dice 类中。
  • 您是否考虑过从Roll() 返回int 结果?此外,Java 方法名称按照约定以小写字母开头。最后,为什么要在未调用的构造函数中初始化静态字段?
  • 已修复,只是我重新输入时出现错误,不是实际问题,谢谢。

标签: java arraylist


【解决方案1】:

您将总计作为静态字段,并且在创建实例时调用的构造函数中对其进行初始化,您需要将其放入静态初始化块中

static {
    totals = new ArrayList<Integer>();
}

在类体内,当你引用其他类的字段时,你需要指定类名,因为它是静态字段,或者使它们成为非静态并通过创建实例来访问它们


【讨论】:

  • 同意,有几个烂摊子@Stephen
  • 或者简单地说,private static ArrayList&lt;Integer&gt; totals = new ArrayList&lt;Integer&gt;();
【解决方案2】:

您应该做出选择:Roll() 是否是静态方法。如果它是静态的(如您的代码所示),那么您需要确保在调用 Dice.Roll() 时已初始化 totals

class Dice
{
private static int x3;
private static ArrayList<Integer> totals=new ArrayList<Integer>();


public static void Roll()
{
int x1 = (int)(Math.random()*6)+1;
int x2 = (int)(Math.random()*6)+1;
x3 = x1 + x2;
totals.add(x3);
}
}

【讨论】:

    【解决方案3】:
    if (totals != null) {
        totals.add(x3);
    } else {
        totals = new ArrayList<Integer>();
        totals.add(x3);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-22
      • 1970-01-01
      • 1970-01-01
      • 2018-07-21
      • 1970-01-01
      相关资源
      最近更新 更多