- /*
- * 问题:我有5个学生,请把这个5个学生的信息存储到数组中,并遍历数组,获取得到每一个学生信息
- * */
- public class Demo2 {
- public static void main(String[] args) {
- Student[] students = new Student[5];
- students[0] = new Student("张三", 22);
- students[1] = new Student("李四", 23);
- students[2] = new Student("王五", 24);
- students[3] = new Student("赵六", 25);
- students[4] = new Student("周八", 26);
- for (int i = 0; i < students.length; i++) {
- System.out.println(students[i].toString());
- }
- }
- }
- class Student {
- private String name;
- private int age;
- 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 String toString() {
- return "Student [name=" + name + ", age=" + age + "]";
- }
- public Student(String name, int age) {
- super();
- this.name = name;
- this.age = age;
- }
- }
复制代码 主要思路是创建好学生类,并定义好相关的方法。然后再添加到数组里面就好了。
|