前言
Java虽然没有直接的结构体概念,但可以通过自定义类实现类似功能,用于封装一组相关联的数据。本笔记通过两个实际编程题目展示如何使用Java类模拟结构体,并完成相应的业务逻辑处理。
题目1:歌唱比赛得分统计(求最高平均分)
题目核心需求
统计n名同学的歌唱比赛得分,每位同学由m名评委打分。得分规则为'去掉一个最高分、一个最低分后求平均值',最终输出所有同学中的最高平均分(保留两位小数)。
解题思路
- 定义
Student类来封装每位学生的评委分数数组、最高分、最低分、总分及平均分。 - 创建n个
Student实例并初始化其分数数组。 - 读取评委打分的同时计算每个学生的最高分、最低分和原始总分,然后扣除极值后计算有效平均分。
- 使用冒泡排序对学生平均分进行升序排列,最后一个元素即为所求最高平均分。
- 格式化输出结果。
核心代码解析
import java.util.Scanner;
class Student {
int[] a; // 存储m名评委的打分
int max = -1; // 最高分,初始值低于最小可能得分(0)
int min = 11; // 最低分,初始值高于最大可能得分(10)
double avg; // 有效平均分(去高低分后)
double sum; // 原始总分
}
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt(); // 学生人数
int m sc.nextInt();
Student[] sts = [n];
( ; i < n; i++) {
sts[i] = ();
sts[i].a = [m];
}
( ; i < n; i++) {
( ; j < m; j++) {
sts[i].a[j] = sc.nextInt();
sts[i].sum += sts[i].a[j];
sts[i].max = Math.max(sts[i].a[j], sts[i].max);
sts[i].min = Math.min(sts[i].a[j], sts[i].min);
}
sts[i].sum -= (sts[i].max + sts[i].min);
sts[i].avg = sts[i].sum * / (m - );
}
( ; i < n - ; i++) {
( ; j < n - - i; j++) {
(sts[j].avg > sts[j + ].avg) {
sts[j];
sts[j] = sts[j + ];
sts[j + ] = temp;
}
}
}
System.out.printf(, sts[n - ].avg);
sc.close();
}
}

