package com.atanjin.exercise;
/*此代码是练习1的一个改进,将操作数组的功能封装到方法中
*
*/
public class MethodExercise2 {
public static void main(String[] args) {
Student2 s[] = new Student2[20];
for(int i = 0;i < s.length;i++) {
s[i] = new Student2();
s[i].score = (int)(Math.random()*100 + 1);
s[i].state = (int)(Math.round(Math.random() * 6 + 0.5));
s[i].number = i + 1;
}
MethodExercise2 test = new MethodExercise2();
test.print(s);
System.out.println("***********************");
test.searchStste(s, 3);
System.out.println("***********************");
test.sort(s);
test.print(s);
}
//遍历Studengt2[]的操作
/**
*
* @Descrition : 遍历数组
* @author AnJin
* @date 2021年3月12日上午10:48:56
* @param s
*/
public void print(Student2 s[]) {
for(int i = 0;i < s.length;i++) {
System.out.println(s[i].info());
}
}
/**
*
* @Descrition : 查找指定年级的学生
* @author AnJin
* @date 2021年3月12日上午10:45:27
* @param s:要查找的数组
* @param state:要查找的年级
*/
public void searchStste(Student2 s[],int state) {
for(int i = 0;i < s.length;i++) {
if(s[i].state == state) {
System.out.println(s[i].info());
}
}
}
/**
*
* @Descrition:给数组排序
* @author AnJin
* @date 2021年3月12日上午10:48:21
* @param s
*/
public void sort(Student2 s[]) {
for(int i = 0;i < s.length - 1;i++) {
for(int j = 0;j < s.length - i - 1;j++) {
if(s[j].score < s[j + 1].score) {
Student2 temp = s[j];
s[j]= s[j + 1];
s[j + 1]= temp;
}
}
}
}
}
class Student2 {
int number;
int state;
int score;
public String info() {
String info = "学号:" + number + "\t年级:" +
state + "\t成绩:" + score;
return info;
}
}