Java-面向对像1-test2

问题:

  1. 对象数组题目:
    定义类Student,包含三个属性:学号number(int),年级state(int),成绩score(int)。
    创建20个学生对象,学号为1到20,年级和成绩都由随机数确定。
    问题一:打印出3年级(state值为3)的学生信息。
    问题二:使用冒泡排序按学生成绩排序,并遍历所有学生信息

提示:

  1. 生成随机数:Math.random(),返回值类型double;
  2. 四舍五入取整: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;
	}
}

总结:

  1. 四舍五入取整:Math.round(double d),返回值类型long。
  2. 数组的类型可以声明为类。
  3. 声明以某个类为类型的数组–>为数组中的每个元素声明对象。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

halisi7

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值