对象数组和for循环遍历输出学生的信息

时间:2023-02-03 22:35:06

public class Student {
private int no;
private String name;
private int age;
public Student(int no, String name, int age) {
// 带参数的构造方法
this.name=name;
this.no=no;
this.age=age;
}
public int getNo() {
return no;
}
public void setNo(int no) {
this.no = no;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}

public class TestStudent {
public static void main(String[] args) {
// TODO 定义对象数组,使用for循环遍历输出每个学生的年龄
Student[] stu = new Student[3];//创建对象数组
//创建学生对象
Student stu1 = new Student(1,"zhangsan",12);
Student stu2 = new Student(1,"zhangsan",12);
Student stu3 = new Student(1,"zhangsan",12);
//把学生对象依次放入数组
stu[0]=stu1;
stu[1]=stu2;
stu[2]=stu3;
//遍历输出学生信息
for (int i = 0; i < stu.length; i++) {
Student s = stu[i];
System.out.println(s.getNo()+" "+s.getName()+" "+s.getAge());;
}
}
}

相关文章