對象數組和for循環遍歷輸出學生的信息


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());;
}
}
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM