问题:
- 对象数组题目:
定义类Student,包含三个属性:学号number(int),年级state(int),成绩score(int)。
创建20个学生对象,学号为1到20,年级和成绩都由随机数确定。
问题一:打印出3年级(state值为3)的学生信息。
问题二:使用冒泡排序按学生成绩排序,并遍历所有学生信息
提示:
- 生成随机数:Math.random(),返回值类型double;
- 四舍五入取整:Math.round(double d),返回值类型long。
代码部分:
public class Student {
public static void main(String[] args) {
//声明Student1数组
Student1[] arr=new Student1[20];
//给数组中的每个元素创建类的对象
for(int i=0;i<arr.length;i++){
arr[i]=new Student1();
//赋值学号
arr[i].number =i+1;
//赋值年级
arr[i].state=(int)(Math.random()*(6-1+1)+1);
//赋值成绩
arr[i].score=(int)(Math.random()*(100-0+1)+0);
}
//创建Student类的对象
Student test=new Student();
//遍历数组
test.print(arr);
System.out.println("********************************");
//问题一:
test.search(arr, 3);
System.out.println("********************************");
//问题二:
test.sort(arr); //排序
test.print(arr);//遍历
}
/**
*
* @description 遍历数组
* @author halisi7 Email:2548825576@qq.com
* @data 2022年1月12日下午1:15:59
* @param arr
*/
public void print(Student1[] arr){
for(int i=0;i<arr.length;i++) {
System.out.println(arr[i].info());
}
}
/**
*
* @description 搜索并输出年纪为t的学生
* @author halisi7 Email:2548825576@qq.com
* @data 2022年1月12日下午1:26:31
* @param arr 搜索的数组
* @param t 需要搜索的年级
*/
public void search(Student1[] arr,int t) {
for(int i=0;i<arr.length;i++) {
if(arr[i].state==t) {
System.out.println(arr[i].info());
}
}
}
//冒泡排序
public void sort(Student1[] arr) {
for(int i=0;i<arr.length-1;i++) {
for(int j=0;j<arr.length-i-1;j++) {
if(arr[j].score<arr[j+1].score) {
Student1 temp;
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
}
//定义Student1类
class Student1{
//s
int number;
int state;
int score;
//
public String info(){
return "学号"+number+"年级"+state+"成绩"+score;
}
}
总结:
- 四舍五入取整:Math.round(double d),返回值类型long。
- 数组的类型可以声明为类。
- 声明以某个类为类型的数组–>为数组中的每个元素声明对象。