面向对象(上)练习一 改进:调用方法

 1 package day1_2;
 2 
 3 /**
 4  * 定义类Student,包含三个属性,学号number(int),年级state(int),分数score(int)
 5  * 创建20个学生对象,学号为1-20号,年级[1,6]和分数[0,100]随机数确定
 6  * 问题一:打印出3年级学生的信息
 7  * 问题二:将学生的成绩按照冒泡排序,并打印学生信息
 8  */
 9 
10 public class ObjectExer2 {
11     public static void main(String[] args) {
12         //声明一个Student类型数组
13         Student1[] stus = new Student1[20];
14         for (int i = 0; i < stus.length; i++) {
15             //每个数组元素引用一个学生对象
16             stus[i] = new Student1();
17             //给每个学生对象属性赋值
18             //学号[1,20]
19             stus[i].number = i+1;
20             //年级[1,6]
21             //Math.random()  返回值double类型  [0,1)
22             //使用公式 (int)(Math.random()*(max-min+1)+min)
23             stus[i].state = (int)(Math.random()*(6-1+1)+1);
24             //成绩[0,100]
25             //Math.random()  返回值double类型  [0,1)
26             //方式一
27             stus[i].score = (int)(Math.random()*(100-0+1));
28             //方式二
29             //Math.round(double n)  返回值long类型  对n进行四舍五入
30             //stus[i].score = (int)Math.round(Math.random()*100);
31         }
32 
33         //static的main方法内调用非static方法,需要创建对象才可以调用
34         ObjectExer2 exer2 = new ObjectExer2();
35         //查看最初学生信息
36         exer2.print(stus);
37         System.out.println("***打印出3年级学生的信息***");
38         //打印出3年级学生的信息
39         exer2.findByState(stus,3);
40         System.out.println("***将学生的成绩按照冒泡排序,并打印学生信息***");
41         //将学生的成绩按照冒泡排序,并打印学生信息
42         exer2.sort(stus);
43         exer2.print(stus);
44     }
45 
46     //遍历学生信息
47     public void print(Student1[] stus){
48         for (int i = 0; i < stus.length; i++) {
49             System.out.println(stus[i].info());
50         }
51     }
52 
53     //打印指定年级的学生信息
54     public void findByState(Student1[] stus, int state) {
55         for (int i = 0; i < stus.length; i++) {
56             if(stus[i].state == state){
57                 System.out.println(stus[i].info());
58             }
59         }
60     }
61 
62     //将学生的成绩按照冒泡排序
63     public void sort(Student1[] stus) {
64         for (int i = 0; i < stus.length - 1; i++) {
65             for (int j = 0; j < stus.length-i-1; j++) {
66                 if (stus[j].score > stus[j+1].score) {
67                     //注意:是交换学生的位置,而不是交换学生的成绩
68                     Student1 tmp = stus[j];
69                     stus[j] = stus[j + 1];
70                     stus[j+1] = tmp;
71                 }
72             }
73         }
74     }
75 
76 
77 }
78 
79 class Student1{
80     int number;//学号
81     int state;//年级
82     int score;//成绩
83 
84     //显示学生信息
85     public String info() {
86         return "学号:" + number + ",班级:"+ state + ",分数:" + score;
87     }
88 }
原文地址:https://www.cnblogs.com/zui-ai-java/p/14224446.html