对象数组输出学生信息

注释内是另外一种方式
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 Student() {
// TODO Auto-generated constructor stub
}
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;
}
}
import java.util.Scanner;

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++) {
stu[i].getAge();
Student s = stu[i];
System.out.println(s.getNo()+" "+s.getName()+" "+s.getAge());;
}
/
Scanner sc = new Scanner(System.in);
Student[] stu = new Student[3];//声明一个对象数组
//循环赋值
for (int i = 0; i < stu.length; i++) {
//学生对象
Student student = new Student();
System.out.println("学号");
int no = sc.nextInt();
System.out.println("学生姓名:");
String name = sc.next();
System.out.println("年龄");
int age = sc.nextInt();
//给属性赋值
student.setName(name);
student.setAge(age);
student.setNo(no);
//把对象添加到数组
stu[i] = student;//stu[0],stu[1],stu[2]
}
showMsg(stu);//调用输出方法
}
static void showMsg(Student[] stu){
for (Student student : stu) {
System.out.println();
System.out.println(student.getNo()+" "+student.getName()+" "+student.getAge());;
}
}
}

原文地址:https://www.cnblogs.com/rainsnow/p/12188111.html