Java使用自定义类数组报空指针异常

一开始自定义了一个学生类,类里面有几个属性。因为有很多个学生,所以想将这个类声明成数组使用,但是当我通过不同的下标给数组里不同对象赋值的时候一直报空指针异常

一开始代码是这样的

package _4_9_test;

public class EightTwoTest {

	public static class Test{
		   String name;
		   int num;
	}
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Test test[] = new Test[2];
		
		test[0].name = "张珊";
		test[0].num = 1;
		
		test[1].name = "李四";
		test[1].num = 2;
		
		System.out.println(test[0].name+" "+test[0].num);
		System.out.println(test[1].name+" "+test[1].num);

	}

}



看了文档后发现**数组的创建不会给数组成员分配内存** 也就是说
Test test[] = new Test[2];

是没有地方可以存数据的。


只有每个成员进行声明后才会给这个成员分配内存

test[0] = new Test();

改良后的代码是这样的

package _4_9_test;

public class EightTwoTest {

	public static class Test{
		   String name;
		   int num;
	}
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Test test[] = new Test[2];
		
		test[0] = new Test();
		test[0].name = "张珊";
		test[0].num = 1;
		
		test[1] = new Test();
		test[1].name = "李四";
		test[1].num = 2;
		
		System.out.println(test[0].name+" "+test[0].num);
		System.out.println(test[1].name+" "+test[1].num);

	}

}

猜你喜欢

转载自www.cnblogs.com/lyd447113735/p/12695345.html