192. 面向对象(上) 练习题-01

192. 面向对象(上) 练习题-01

Test类

package person;
/**
    定义类Student,包含三个属性:学号number(int),年级state(int)(1-3年级),成绩
    score(int)。创建20个学生对象,学号为1到20,年级和成绩都由随机数确定。

    问题一:打印出3年级(state值为3)的学生信息。

	问题二:使用冒泡排序按学生成绩排序,并遍历所有学生信息提示:
	
	问题三: 把遍历数组, 显示年级成绩, 排序成绩封装为方法.

	1)生成随机数:Math.random(),返回值类型double; 2)四舍五入取整:Math.round(double d),返回值类型long。
	(int)(Math.random*(b-a+1)+a);(范围a-b)
 */
public class Test {
	public static void main(String[] args) {
		
			Student[] stu = new Student[20];  			//声明对象数组  stu
			for(int i = 0 ; i < stu.length ; i ++) {
				stu[i] = new Student();					//声明数组每个对象
			}
			
			for(int i = 0 ; i < stu.length; i++) {		
				stu[i].number = i+1;								//给number属性赋值
				stu[i].state = (int)(Math.random()*(3-1+1)+1);		//给state属性赋值
				stu[i].score = (int)(Math.random()*(100+1));		//给score属性赋值
			}
			Test test=new Test();
			System.out.println("*************顺序排列**************");
			test.print(stu);
			
			System.out.println("^^^^^^^^^^^^^年级成绩^^^^^^^^^^^^^^");
			test.printSt(stu, 1);
			
			System.out.println("*************总成绩排名*************");
			test.sort(stu);
			test.print(stu);
	}
			
	//***********方法************
	/**
	 * @Description 遍历数组
	 * @author babyCheetah
	 * @date 2022年10月16日下午3:34:49
	 * @param stu 	数组
	 */
	void print(Student []stu) {
		for(int i = 0 ; i <stu.length; i++ ) {
			System.out.println(stu[i].info());
		}
	}
	/**
	 * @Description 显示年级成绩
	 * @author babyCheetah
	 * @date 2022年10月16日下午3:32:50
	 * @param	stu		数组
	 * @param	num		要查找的年级
	 * @return
	 */
	void printSt(Student []stu, int num) {
		for(int i = 0 ; i < stu.length; i++) {
			if(stu[i].state==num) {
				System.out.println(stu[i].info());
			}
		}
	}
	/**
	 * @Description 排序方法
	 * @author babyCheetah
	 * @date 2022年10月16日下午3:29:53
	 * @param	stu[] 	要排序的数组 
	 */
	void sort(Student stu[]) {
		for(int i=0;i<stu.length-1;i++) {
			for(int j=0;j<stu.length-1-i;j++) {
				if(stu[j].score>stu[j+1].score) {
					Student temp=stu[j];
					stu[j]=stu[j+1];
					stu[j+1]=temp;
				}
			}
		}
	}
}

Student类

package person;
public class Student {
		int number;//學號
		int state;//年级
		int score;//成绩
		//显示一个学生信息
		public String info() {
			return "学号: "+ number +"  年级: "
		+state+"  成绩: " +score;
		}
}
posted @ 2022-10-16 21:20  大宝贝94106  阅读(54)  评论(0)    收藏  举报