作业:
1.创建一个学生类型,包括姓名(字符串类型),性别(字符型),考试成绩(整数数组,长度为10)
2.创建方法,计算平均分(去掉一个最高分,去掉一个最低分,剩余的取平均分)
3.编写一个方法,参数为学生数组,根据学生的平均成绩,按高到低排序。
package lession0712;
public class Student {
private String name;
private char sex;
private int age;
private int[] score = new int[10];
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public char getSex() {
return sex;
}
public void setSex(char sex) {
this.sex = sex;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int[] getScore() {
return score;
}
public void setScore(int[] score) {
this.score = score;
}
// 计算最大值
public int getMax() {
int max = score[0];
for (int i = 0; i < score.length; i++) {
if (score[i] > max) {
max = score[i];
}
}
return max;
}
// 计算最小值
public int getMin() {
int min = score[0];
for (int i = 0; i < score.length; i++) {
if (score[i] < min) {
min = score[i];
}
}
return min;
}
// 计算总分
public int getTotal() {
int sum = 0;
for (int i = 0; i < score.length; i++) {
sum += score[i];
}
return sum;
}
// 计算平均分
public double avg() {
return 1.0 * (this.getTotal() - this.getMax() - this.getMin()) / (score.length - 2);
}
}
package lession0712;
import java.util.Scanner;
public class Zhu {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("请输入学生个数(1-9):");
int n = scan.nextInt();
Student[] stu = new Student[n];
for (int k = 0; k < n; k++) {
stu[k] = new Student();
stu[k].setName(f1(3));
char[] sex = { '男', '女' };
stu[k].setSex(sex[(int) (Math.random() * 2)]);
int[] score = new int[10];
for (int j = 0; j < 10; j++) {// 把第k个同学的成绩j随机从40-100赋值
score[j] = (int) (Math.random() * 60 + 40);
}
stu[k].setScore(score);
}
for (int i = 0; i < n; i++) {
System.out.println("第" + (i + 1) + "个学生:");
System.out.print("姓名:" + stu[i].getName() + " ");
System.out.print("姓别:" + stu[i].getSex() + " ");
System.out.print("成绩: ");
for (int j = 0; j < stu[i].getScore().length; j++) {
System.out.print(stu[i].getScore()[j] + " ");
}
System.out.println();
}
sort(stu);
scan.close();
}
public static void sort(Student[] students) {
for (int i = 0; i < students.length - 1; i++) {
for (int j = i + 1; j < students.length; j++) {
if (students[j].avg() > students[i].avg()) {
Student t = students[i];
students[i] = students[j];
students[j] = t;
}
}
}
System.out.println();
System.out.println("根据学生的平均成绩,按高到低排序:");
for (int i = 0; i < students.length; i++) {
System.out.print("第" + (i + 1) + "名:" + students[i].getName() + " " + " 性别:" + students[i].getSex());
System.out.print(" 成绩:");
for (int j = 0; j < students[i].getScore().length; j++) {
System.out.print(students[i].getScore()[j] + " ");
}
System.out.println(" 平均分" + students[i].avg());
}
}
private static String f1(int t) {
String s = new String();
for (int j = 0; j < t; j++) {
char c = (char) (Math.random() * 25 + 97);
s += c;
}
return s;
}
}
输出结果: