gpt4 book ai didi

java - 复制到带有字符串的类时出现空指针异常

转载 作者:行者123 更新时间:2023-12-01 11:06:13 24 4
gpt4 key购买 nike

我在这个论坛上看到过其他帖子,该解决方案是统一的 String .

为什么这会返回 null pointer exception ,因为我正在初始化字符串和 Foo 的数组?

class Foo
{
public String Name = "foobar";
public int Score = 0;
};

class Bar
{
private Foo[] timerScore = new Foo[10];

//....

private void xpto()
{
timerScore[0].Name = "test"; //<---null pointer exception.why?!
timerScore[0].Score = 30;
}
}

最佳答案

创建 Foo 数组并不会创建 Foo 的实际实例。

您需要:

private void xpto()
{
timerScore[0] = new Foo ();
timerScore[0].Name = "test";
timerScore[0].Score = 30;
}

关于java - 复制到带有字符串的类时出现空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32914784/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com