我有一个包含这些属性和方法的java对象:
public class Student {
private String name;
private String surname;
private int age;
private int[] qualifications = new int[4];
}
public Student(String name, String surname, int age, int[] qualifications){
this.name = name;
this.surname = surname;
this.age = age;
this.qualifications = qualifications;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int[] getQualifications () {
return qualifications;
}
public void setQualifications(int[] qualifications) {
this. qualifications = qualifications;
}
我使用:
初始化对象的实例Student a1 = new Student("John","Doe",32,new int[]{10,8,9,9});
我尝试获取并设置名称和资格。使用name属性,但它不适用于资格数组。
// it works
a1.setName("Tom");
System.out.println("Name of the student: "+a1.getName());
//it doesn't work
System.out.println("Qualifications of the student: "+a1.getQualifications());
//return:
[I@15db9742
谢谢!
答案 0 :(得分:1)
如果“不起作用”,则表示您获得的输出如下:
学生资格:[I @ 368102c8
然后“修复”是使用Arrays.toString
来打印数组:
System.out.println("Qualifications of the student: " + Arrays.toString(a1.getQualifications());
这将输出:
学生资格:[10,8,9,9]
如果你想摆脱封闭的[...]
,
然后使用String.substring
,例如:
String arrstr = Arrays.toString(a1.getQualifications());
System.out.println("Qualifications of the student: " + arrstr.substring(1, arrstr.length() - 1));
这将输出:
学生资格:10,8,9,9
答案 1 :(得分:0)
要打印您使用Arrays.toString(array)
的数组元素,a1.getQualifications()
将返回toString
方法的默认实现