我最近在学习Java,并且正在尝试使用类。但是我无法初始化数组对象
class Tablet
{
String S = null;
void set(String a)
{
S = a;
}
}
public class questions
{
public static void main(String args[])
{
Tablet[] T = new Tablet[6];
for(int i = 0;i<6;i++)
{
T[i].set("111"); // I get null pointer exception here
}
//solution(T,6);
}
}
谁能告诉我哪里出错?
答案 0 :(得分:3)
当你这样做时
Tablet[] T = new Tablet[6];
您正在创建引用数组(即引用变量数组),它们没有指向其他地方,即它们为null。您需要将对象分配给数组中上面创建的引用变量。
Tablet[] T = new Tablet[6];
for(int i = 0;i<6;i++)
{
T[i]=new Tablet();
T[i].set("111"); // No Null Pointer Exception Now
}
答案 1 :(得分:2)
您需要初始化数组的索引
class Tablet {
String S = null;
void set(String a) {
S = a;
}
}
class questions {
public static void main(String args[]) {
Tablet[] T = new Tablet[6];
for (int i = 0; i < 6; i++) {
T[i] = new Tablet();
T[i].set("111"); // I get null pointer exception here
}
//solution(T,6);
}
}
答案 2 :(得分:1)
您创建了一个数组(多个Tablet
个对象的持有者),但实际上并没有创建任何Tablet
进入其中。现在,T
(实际上应该是小写的; T
看起来像是常量和类型参数)具有以下内容:
T: {null, null, null, null, null, null}
您需要创建new Tablet
并将它们放入数组中,可能是这样的:
for(int i = 0; i < array.length /* don't hardcode the size twice */; i++) {
array[i] = new Tablet();
array[i].set("111");
}
答案 3 :(得分:0)
您已初始化数组。但是,数组中的元素指向null。所以很明显,如果您尝试在空指针上调用方法,则会得到一个空指针异常。 您必须使用new关键字初始化数组中的每个对象。
您必须添加一个T [i] = new Tablet();在对该变量执行任何功能之前先对其进行初始化。
T[i]=new Tablet();
T[i].set("111");
在for循环中执行此操作