我有2个班级,一流的学院和第二个讲师。 在大学课堂上我有>> public Lecturer [] allLecturer;
我希望大学系接收讲师部门,但是当我试图打印大学系时,我有些奇怪。
班级讲师:
public class Lecturer {
public String name;
public int numOfTimesPenFalls;
public String favoriteIceCream;
public int autoNumber;
//constructor
public Lecturer(String Name, int NumOfTimesPenFalls,
String FavoriteIceCream, int AutoNumber) {
this.name = Name;
this.numOfTimesPenFalls = NumOfTimesPenFalls;
this.favoriteIceCream = FavoriteIceCream;
this.autoNumber = AutoNumber;
}
@Override
public String toString(){
return "name: " +name+ " num Of Times Pen Falls: "+ numOfTimesPenFalls +
" favorite Ice Cream: " + favoriteIceCream + " auto Number: " + autoNumber;
}
}
班级学院:
public class College {
public String name;
public int numOfLecturer;
public Lecturer[] allLecturer;
public int maxLecturer;
//constructor
public College(String Name, int NumOfLecturer, Lecturer[] AllLecturer, int MaxLecturer) {
this.name = Name;
this.numOfLecturer = NumOfLecturer;
this.allLecturer = AllLecturer;
this.maxLecturer = MaxLecturer;
}
public College(String Name){
this.name = Name;
}
@Override
public String toString(){
return "Name College: " +name+ " num Of Lecturer: " + numOfLecturer +
" all Lecturer: " + allLecturer + " max Lecturer " + maxLecturer ;
}
}
主:
public class main {
public static void main(String[] args) {
Lecturer[] L1 = new Lecturer[] { new Lecturer("David", 3, "Banana",
1001) };
College myCollege = new College("College1", 20, L1, 10);
System.out.println(myCollege.toString());
}
}
结果输出:
Name College: College1 num Of Lecturer: 20 all Lecturer: [LLecturer;@139a55 max Lecturer 10
为什么它给我打印([LLecturer; @ 139a55]而不是部门的详细信息?
如果我在main for循环中写道:
for (int i = 0; i < L1.length; i++) {
System.out.println(L1[i]);
}
结果输出:
name: David num Of Times Pen Falls: 3 favorite Ice Cream: Banana auto Number: 1001
如何解决此问题,以便在我打印课程(System.out.println(myCollege.toString()) );
时
我还打印了讲师部门的信息?
答案 0 :(得分:0)
答案 1 :(得分:0)
Java数组不会覆盖Object
的toString()方法。只需将您编写的循环添加到College
示例解决方案:
@Override
public String toString(){
return "Name College: " +name+ " num Of Lecturer: " + numOfLecturer +
" all Lecturer: " + java.util.Arrays.toString(allLecturer) + " max Lecturer " + maxLecturer ;
}
如果您可以使用第三方库,请查看Apache的StringUtils
类,它有一个方便的join()
方法,可以从连续的对象数组中生成一个String
答案 2 :(得分:0)
将toString()
中的College.java
方法更改为
@Override
public String toString(){
return "Name College: " +name+ " num Of Lecturer: " + numOfLecturer +
" all Lecturer: " + Arrays.toString(allLecturer) + " max Lecturer " + maxLecturer ;
}
并在您的主要方法中尝试打印您的College
参考
College myCollege = new College("College1", 20, L1, 10);
System.out.println(myCollege);
现在你的输出是:
Name College: College1 num Of Lecturer: 20 all Lecturer: [name: David num Of Times Pen Falls: 3 favorite Ice Cream: Banana auto Number: 1001] max Lecturer 10