我在我的类中声明了一个String数组而没有初始化它,然后我创建了一个函数来填充这个名为“FillFacts”的数组。问题是,当我调用应该返回我的数组的函数时,它返回NullPointerException。 问题是如何在函数内部初始化我的数组,因为我已经测试过在声明部分初始化它,如下所示:
private String[] facts = {"fact1", "fact2", "fact3"};
它有效,但我不想这样使用它。
代码来源:
import java.util.Random;
public class Facts {
private String[] facts;
private String[] colors;
private String fact, color;
private Random random = new Random();
private int random_number;
public void Facts() {
this.random = new Random();
this.random_number = 0;
FillFacts();
FillColors();
}
public void FillFacts() {
facts = new String[] {"smartphone android has a home button", "every Iphone has a memory in his heart!", "cubes can be rotated in 180 degree", "banana has a yellow color", "wacom tablet are linked with usb cable"};
}
public void FillColors() {
colors = new String[] {"#34495e", "#3498db", "#1abc9c", "#e74c3c", "#f1c40f", "#95a5a6", "#d35400"};
}
public String PickRandomFact() {
random_number = random.nextInt(facts.length) ;
fact = facts[random_number];
return fact;
}
public String PickRandomColor() {
random_number = random.nextInt(colors.length);
color = colors[random_number];
return color;
}
public String getColor() {
return color;
}
}
答案 0 :(得分:0)
Tick
不是构造函数,因此在创建void Facts()
实例时不执行(这就是为什么Facts
和FillFacts
未执行)。构造函数没有返回类型。
更改
FillColors
到
public void Facts()
答案 1 :(得分:0)
您应该更改constructor
无效:
public void Facts() {
喜欢这个:
public Facts() {