/* * 我有5个学生,请把这个5个学生的信息存储到数组中,并遍历学生数组,获取得到每一个学生的信息。 * 学生类:Student * 成员变量:name,age * 构造方法:无参,带参 * 成员方法:getXxx()/setXxx() * 存储学生的数组?自己想想应该是什么样子的? * 分析: * A:创建学生类。 * B:创建学生数组(对象数组)。 * C:创建5个学生对象,并赋值。 * D:把C步骤的元素,放到学生数组中。 * E:遍历学生数组。 */
示例代码如下:
1 package cn.itcast_01;
2
3 public class Student {
4 // 成员变量
5 private String name;
6 private int age;
7
8 // 构造方法
9 public Student() {
10 super();
11 }
12
13 public Student(String name, int age) {
14 super();
15 this.name = name;
16 this.age = age;
17 }
18
19 // 成员方法
20 // getXxx()/setXxx()
21 public String getName() {
22 return name;
23 }
24
25 public void setName(String name) {
26 this.name = name;
27 }
28
29 public int getAge() {
30 return age;
31 }
32
33 public void setAge(int age) {
34 this.age = age;
35 }
36
37 @Override
38 public String toString() {
39 return "Student [name=" + name + ", age=" + age + "]";
40 }
41 }
1 package cn.itcast_01;
2
3 /*
4 * 我有5个学生,请把这个5个学生的信息存储到数组中,并遍历学生数组,获取得到每一个学生的信息。
5 * 学生类:Student
6 * 成员变量:name,age
7 * 构造方法:无参,带参
8 * 成员方法:getXxx()/setXxx()
9 * 存储学生的数组?自己想想应该是什么样子的?
10 * 分析:
11 * A:创建学生类。
12 * B:创建学生数组(对象数组)。
13 * C:创建5个学生对象,并赋值。
14 * D:把C步骤的元素,放到学生数组中。
15 * E:遍历学生数组。
16 */
17 public class ObjectArrayDemo {
18 public static void main(String[] args) {
19 // 创建学生数组(对象数组)。
20 Student[] students = new Student[5];
21
22 // 遍历新创建的学生数组。
23 for (int x = 0; x < students.length; x++) {
24 System.out.println(students[x]);
25 }
26 System.out.println("---------------------");
27
28 // 创建5个学生对象,并赋值。
29 Student s1 = new Student("林青霞", 27);
30 Student s2 = new Student("风清扬", 30);
31 Student s3 = new Student("刘意", 30);
32 Student s4 = new Student("赵雅芝", 60);
33 Student s5 = new Student("王力宏", 35);
34
35 // 把C步骤的元素,放到学生数组中。
36 students[0] = s1;
37 students[1] = s2;
38 students[2] = s3;
39 students[3] = s4;
40 students[4] = s5;
41
42 // 看到很相似,就想用循环改,把C步骤的元素,放到学生数组中。
43 // for (int x = 0; x < students.length; x++) {
44 // students[x] = s + "" + (x + 1); // 拼完之后是一个字符串了。
45 // }
46 // 这个是有问题的。
47
48 // 遍历赋值后的学生数组。用重写toString()方法
49 for (int x = 0; x < students.length; x++) {
50 // 重写toString()方法,注意:一个方法写定之后就不要再去改变了。因为改来改去的还不如重新写个方法呢?
51 System.out.println(students[x]);
52 }
53 System.out.println("---------------------");
54
55 // 遍历赋值后的学生数组,用getXxx()方法
56 for (int x = 0; x < students.length; x++) {
57 // 因为学生数组的每一个元素都是一个学生。
58 Student s = students[x];
59 System.out.println(s.getName()+"---"+s.getAge());
60 }
61 }
62 }
1 null
2 null
3 null
4 null
5 null
6 ---------------------
7 Student [name=林青霞, age=27]
8 Student [name=风清扬, age=30]
9 Student [name=刘意, age=30]
10 Student [name=赵雅芝, age=60]
11 Student [name=王力宏, age=35]
12 ---------------------
13 林青霞---27
14 风清扬---30
15 刘意---30
16 赵雅芝---60
17 王力宏---35