数组的元素可以是基本数据类型,也可以是引用数据类型。当元素是引用类型
中的类时,我们称为对象数组。
举例:
Student类
package com.atguigu.oop;
/**
* ClassName:Student
* Package:com.atguigu.oop
*
* @Description: 定义类Student,包含三个属性,state(年级)、score(成绩)、number(学号)
* @Author 文歆
* @Create 2023/6/12 14:15
* @Version 1.0
*/
public class Student {
//属性
int number; //学号
int state; //年级
int score; //成绩
public String show(){
return "number:" + number + ",state:" + state + ",score" + score;
}
}
Student的测试类 StudentTset
package com.atguigu.oop;
/**
* ClassName:StudentTest
* Package:com.atguigu.oop
*
* @Description:
* @Author 文歆
* @Create 2023/6/12 14:15
* @Version 1.0
*/
public class StudentTest {
public static void main(String[] args) {
//动态初始化方式创建数组长度为10的数组
// int[] arr = new int[10];
//通过循环给数组元素赋值
// for (int i = 0; i < arr.length; i++) {
// arr[i] = (int)(Math.random() * (99 -10 + 1)) + 10;
// System.out.println(arr[i] + "\t");
// }
//创建Student[]
Student[] students = new Student[20];
//使用循环给数组元素赋值
for(int i = 0; i < students.length; i++){
students[i] = new Student();
//给每一个学生对象的number、state、score属性赋值
students[i].number = i + 1;
students[i].state = (int)(Math.random() * 6 + 1);
students[i].score = (int)(Math.random() * 101);
}
//需求1:打印出3年级(state值为3)的学生信息
for (int i = 0; i < students.length; i++){
if (students[i].state == 3){
Student stu = students[i];
System.out.println(stu.show());
}
}
}
}