如何在二维数组中分离不同的值 [英] How to separate different values in 2-d array
问题描述
该数组具有来自不同子类的对象。如何根据那里的子类打印对象?
我用扫描仪读取学生(研究生和本科生)的对象并放入数组中。
我需要使用继承和toString方法来获取结果。
txt文件中的原始数据:
G Steve 23 Biology
U Julia 19音乐长笛,年:大二
G David 25 Math
能够读取和打印对象,但只能以原始顺序进行:
毕业生姓名:Steve,年龄:23岁,专业:生物学
本科名称:朱莉娅,年龄:19,专业:音乐,年:大二
毕业生名称:Dvid,年龄:25,专业:数学
下面是我在测试程序文件中使用的方法:
ArrayList< Student> studentList = new ArrayList<>();
学生s =新本科生(类型,姓名,年龄,专业,年份);
studentList.add(s);
学生s =新毕业生(类型,姓名,年龄,专业);
studentList.add(s);
for(学生d:studentList){
System.out.println(d.toString());
}
===
预期结果:===
本科生人数:1
姓名:朱莉娅,年龄:19,专业:音乐,年份:大二p>
研究生人数:2
姓名:Steve,年龄:23,专业:生物学
姓名:Dvid,年龄:25,专业:数学
===
这是我在这里的第一个问题。我对系统不熟悉。我试图使我的问题更容易阅读。抱歉,如果看起来很乱。
您可以使用instanceof来分隔不同类型的对象。
ex。
如果(以本科生为例){
本科生u =(本科生)s;
}
您可以使用instanceof迭代列表并计算对象数。
您也可以在输入期间进行上面的检查。
The array has objects from different subclasses. How can I print the objects according to there subclasses?
I used scanner to read student (Graduate and Undergraduate) objects and put into an array.
I need to use inheritance and toString methods to get the results.
Original data in txt file:
G Steve 23 Biology
U Julia 19 Music Flute, year: Sophomore
G David 25 Math
I was able to read and print the objects but only in original order:
Graduate Name:Steve, Age: 23, Major: Biology
Undergraduate Name: Julia, Age: 19, Major: Music, year: Sophomore
Graduate Name: Dvid, Age: 25, Major: Math
Below is the method I used in tester file:
ArrayList<Student> studentList = new ArrayList<>();
Student s = new Undergraduate(type,name,age,major,year);
studentList.add(s);
Student s = new Graduate(type,name,age, major);
studentList.add(s);
for (Student d:studentList) {
System.out.println(d.toString());
}
=== Expected result:===
Number of Undergraduate Student: 1
Name: Julia, Age: 19, Major: Music, year: Sophomore
Number of Graduate Student: 2
Name:Steve, Age: 23, Major: Biology
Name:Dvid, Age: 25, Major: Math
===
This is my first question here. I am not familiar with the system. I tried to make my question easier to read. Sorry if it looks messy.
You can use instanceof to separate the different types of objects. ex.
if (s instanceof Undergraduate){
Undergraduate u = (Undergraduate) s;
}
You can iterate your list and count your objets using instanceof. You can do the check above during the input too.
这篇关于如何在二维数组中分离不同的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!