Java输出对象的数组是地址,如何输出其值?

2025-03-13 01:22:12
推荐回答(4个)
回答1:

可以重写Student类中的toString()方法,以下例子仅作为参考:

class Student
{
//该类的实例变量
public String no;
public String name;
public String sex;
public int yuwen;
public int shuxue;
public int yingyu;
public int lizong;

//创建构造器
public Student(String no , String name , String sex , int yuwen , int shuxue , int yingyu , int lizong){
this.no = no;
this.name = name;
this.sex = sex;
this.yuwen = yuwen;
this.shuxue = shuxue;
this.yingyu = yingyu;
this.lizong = lizong;
}

//重写toString()方法,该方法输出对象
public String toString(){
return "Student[no: " + no + " , name: " + name +" , sex: " + sex + " , yuwen: " + yuwen + " , shuxue: " + shuxue + " , yingyu: " + yingyu + " , lizong: " + lizong + " ]";
}
}
public class Student1 
{
public static void main(String[] args) 
{
Student stu1 = new Student("001","Zhang","男",65,70,53,80);
Student stu2 = new Student("002","Cheng","女",75,75,85,78);
Student stu3 = new Student("003","Li","女",68,45,95,72);
Student stu4 = new Student("004","Cha","男",67,70,64,62);
Student stu5 = new Student("005","Xun","男",65,90,78,85);
Student []st = {stu1,stu2,stu3,stu4,stu5};
for(Student c:st){
System.out.println(c);
}
}
}

回答2:

数组中存放的是student对象,输出
(c)就是输出对象student。
如果想输出单个变量 例如姓名,print(c.getName())类似这样。
多个就可以print(c.get.....c.get)
当然有更优雅的方式。
从上面可以看出来c.getName()是调用了姓名的get方法。
你在student里面定义一个方法printMsg(),方法里有一行代码。
打印student所有变量。
for循环里调用c.printMsg()就打印出来了。

回答3:

输出数组值应该是数组名+[下标名]   比如st[c]  或者st[0] st[1] st[2]

回答4:

for(int i=0;i<=st.length;i++){
System.out.print(st[i]);