可以将类名用作数组的数据类型吗?

huangapple 未分类评论55阅读模式
英文:

Can a class name be used as a datatype for an array?

问题

我尝试执行了以下代码:

public class Phonebook {
    String name;
    long phno;
}

public class Store {
    public static void main(String args[]) {		
        Phonebook p[] = new Phonebook[10];

        p[0].name = "vasvi";
        p[0].phno = 123456;
        p[1].name = "abcd";
        p[2].phno = 903747;

        System.out.println(p[0].name + " " + p[1].name);
    }
}

执行此代码会出现 NullPointerException。我似乎不明白为什么会出现这样的异常。我已经学到了类是用户定义的数据类型。所以我真的很困惑为什么会出现这样的异常?

英文:

I tried executing the following code

public class Phonebook {
	String name;
	long phno;
}

public class Store {
    public static void main(String args[]) {		
    	Phonebook p[] = new Phonebook[10];
    		
        p[0].name = "vasvi";
    	p[0].phno = 123456;
    	p[1].name = "abcd";
    	p[2].phno = 903747;
    		
        System.out.println(p[0].name + " " + p[1].name);
    }
}

This code when executed gives the NullPointerException. I don't seem to understand why. I have learnt that classes are user defined data types. So I'm really confused why such an exception would arise?

答案1

得分: 0

看起来你还没有初始化你的数组。

英文:

it looks like you have not initialized you array.

huangapple
  • 本文由 发表于 2020年4月7日 22:00:13
  • 转载请务必保留本文链接:https://java.coder-hub.com/61081783.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定