我初次接触java,遇到一个问题
public class Main {
public static void main(String[] args) {
// TODO code application logic here
Supplement[] Sup = new Supplement[5];
Sup[1] = new Supplement("PlayBoy", 5);
Customer[] Cus = new Customer[10];
Cus[1]=new Customer("Peter", "[email protected]", "Paying", "N.A.", Sup );
// Scanner keyboard = new Scanner(System.in); for (int i=0; i<2; i++)
{
System.out.println(Cus[i].name+"***"+Cus[i].email+"***"+Cus[i].type+"***"+Cus[i].AssCus);
for (int z=0; z<2; z++)
{
// System.out.println(Cus[i].sup[z].name + "\n" + Cus[i].sup[z].cost);
}
}
}public class Customer {
public String name;
public String email;
public String type;
public Supplement[] sup;
public String AssCus; public Customer (String name, String email, String type, String AssCus, Supplement[] sup)
{
this.name = name;
this.email = email;
this.type = type;
this.AssCus = AssCus;
this.sup = sup;
}}为什么会出现Exception in thread "main" java.lang.NullPointerException
但如果这样写System.out.println(Cus[1].name+"***"+Cus[1].email+"***"+Cus[1].type+"***"+Cus[1].AssCus);却没问题
public class Main {
public static void main(String[] args) {
// TODO code application logic here
Supplement[] Sup = new Supplement[5];
Sup[1] = new Supplement("PlayBoy", 5);
Customer[] Cus = new Customer[10];
Cus[1]=new Customer("Peter", "[email protected]", "Paying", "N.A.", Sup );
// Scanner keyboard = new Scanner(System.in); for (int i=0; i<2; i++)
{
System.out.println(Cus[i].name+"***"+Cus[i].email+"***"+Cus[i].type+"***"+Cus[i].AssCus);
for (int z=0; z<2; z++)
{
// System.out.println(Cus[i].sup[z].name + "\n" + Cus[i].sup[z].cost);
}
}
}public class Customer {
public String name;
public String email;
public String type;
public Supplement[] sup;
public String AssCus; public Customer (String name, String email, String type, String AssCus, Supplement[] sup)
{
this.name = name;
this.email = email;
this.type = type;
this.AssCus = AssCus;
this.sup = sup;
}}为什么会出现Exception in thread "main" java.lang.NullPointerException
但如果这样写System.out.println(Cus[1].name+"***"+Cus[1].email+"***"+Cus[1].type+"***"+Cus[1].AssCus);却没问题
Sup[1] = new Supplement("PlayBoy", 5);
数组的下标是从0开始,不是1
明白么?
Cus[1]=new Customer("Peter", "[email protected]", "Paying", "N.A.", Sup );
其它的呢?比如Cus[0]等等呢?在你下面的循环
for (int i=0; i <2; i++) {
System.out.println(Cus[i].name+"***"+Cus[i].email+"***"+Cus[i].type+"***"+Cus[i].AssCus);
这里Cus[0]里都是null,当然会抛出空指针了。