Java 访问对象[]数组成员的方法
我必须创建一个对象数组,然后随机填充。在这个数组中,我需要随机放置100个,个人(基本)学生(sub),教授(sub),课程(学生加教授的数组)和一个圆圈(无关)。我还必须对我进入数组的每个人(包括教授和学生)进行命名和计数Java 访问对象[]数组成员的方法,java,arrays,object,cannot-find-symbol,Java,Arrays,Object,Cannot Find Symbol,我必须创建一个对象数组,然后随机填充。在这个数组中,我需要随机放置100个,个人(基本)学生(sub),教授(sub),课程(学生加教授的数组)和一个圆圈(无关)。我还必须对我进入数组的每个人(包括教授和学生)进行命名和计数 Object[] array = new Object[100]; String[] names = new String[]{"Ben","Anne","Joe","Sue","John","Betty","Robert","Mary",
Object[] array = new Object[100];
String[] names = new String[]{"Ben","Anne","Joe","Sue","John","Betty","Robert","Mary",
"Mark","Jane","Paul","Willow","Alex","Courtney","Jack",
"Rachel"};
int count = 0;
for(int i=0; i<100; i++){
int a = (int)(Math.random()*5);
String n = names[(int)(Math.random()*16)];
if(a == 0){array[i]= new Person(n); count++;}
else if(a == 1){array[i]= new Student(n); count++;}
else if(a == 2){array[i]= new Professor(n); count++;}
else if(a == 3){
array[i]= new Course();
count = count + 11;
for(int j = 0; j<10; j++){
String l = names[(int)(Math.random()*16)];
array[i].getClasslist()[j].setName(l);}
}
else if(a == 4){array[i]= new Circle();}
}
Object[]数组=新对象[100];
字符串[]名称=新字符串[]{“本”、“安妮”、“乔”、“苏”、“约翰”、“贝蒂”、“罗伯特”、“玛丽”,
“马克”、“简”、“保罗”、“柳树”、“亚历克斯”、“考特尼”、“杰克”,
“雷切尔”};
整数计数=0;
对于(int i=0;i,就您的实际代码而言,您需要以编写它的方式显式地强制转换array[i]
:
for(int j = 0; j<10; j++){
String l = names[(int)(Math.random()*16)];
((Course) array[i]).getClasslist()[j].setName(l);
}
for(int j=0;j当有一系列混合对象时,必须先检查对象的实际类型,然后才能调用特定类型的方法。为此,请使用instanceof
:
for (Object obj : array) {
if (obj instanceof Person) { // includes subclasses Student and Professor
Person person = (Person)obj;
// now you can call Person methods
} else if (obj instanceof Course) {
Course course = (Course)obj;
for (Object member : course.getMembers()) {
if (member instanceof Person) {
Person person = (Person)member;
// now you can call Person methods
}
}
}
}
我认为将所有这些不同的类放在一个对象[]
中是完全可以的,只要在程序的后面部分,数组的所有元素都只用作对象(好吧,对象
不是一个花哨的接口,但这只是一个练习)
但最好初始化整个过程
对象,然后将其放入数组:
else if(a == 3){
Course course = new Course();
count = count + 11;
for(int j = 0; j<10; j++){
String l = names[(int)(Math.random()*16)];
course.getClasslist()[j].setName(l);//no casting needed
}
array[i]=course;//we can forget the real type of the object now
}
else如果(a==3){
课程=新课程();
计数=计数+11;
对于(int j=0;j)在一个数组中混合不同类型的对象而没有任何公共接口通常表明您的设计中存在严重问题。您确定这就是您的任务要求您做的吗?我刚刚回到stackoverflow,意识到我从来没有因为您的回答而表扬过您。迟做总比不做强!