public class B {
private int[] a;
private int[] c;
B(int[] a, int d){
this.a = a;
for(int i=0; i<d; d++){
c[i] = a[i];
}
}
public int[] getA() {
return a;
}
public void setA(int[] a) {
this.a = a;
}
}
public class A {
public static void main(String[] args) {
int[] b1;
b1 = new int[3];
b1[0] = 1;
b1[1] = 2;
b1[2] = 3;
B b =new B(b1,3);
int[] t = b.getA();
for(int i=0;i<3; i++){
System.out.println(t[i]);
}
}
}
运行时报错如下:
Exception in thread "main" java.lang.NullPointerException
at B.<init>(B.java:8)
at A.main(A.java:10)
找不出是什么原因,求帮忙!
------最佳解决方案--------------------------------------------------------
数组是引用类型的,成员变量默认初始化为null。
------其他解决方案--------------------------------------------------------
class B 中的数组要赋值长度的。。
private int[] a=new int[3];
private int[] c=new int[3];
------其他解决方案--------------------------------------------------------
在this.a = a;
后面加上 c = new int[d];
------其他解决方案--------------------------------------------------------
class B里面
....
for(int i=0; i<d; d++)
....
没搞懂,LZ能说说么?
------其他解决方案--------------------------------------------------------
+1
------其他解决方案--------------------------------------------------------
int[] c;
他的初始化长度为0,没有给定长度,你赋值的时候编译器找不到索引,也就是c[0]/c[1]/c[2]
------其他解决方案--------------------------------------------------------
解决了,谢谢!
有时间的话,能解释一下吗?