java统计学生出勤次数,n个学生,每个学生有学号和出勤记录,该记录为10位二进制位串,1为出勤,0为未出勤。 按出勤次数降序排列输出,如果出勤次数相同,按学号从小到大排序。
时间: 2023-09-29 22:10:55 浏览: 60
可以使用一个Map来记录每个学生的出勤次数,然后将Map中的记录按照出勤次数和学号排序输出即可。
代码如下:
```java
import java.util.*;
public class AttendanceCounter {
public static void main(String[] args) {
int n = 5; // 假设有5个学生
Map<String, Integer> attendanceCount = new HashMap<>(); // 存放每个学生的出勤次数
// 模拟随机生成每个学生的出勤记录
Random random = new Random();
for (int i = 0; i < n; i++) {
String studentId = "S" + i; // 学号为S0、S1、S2...
StringBuilder attendanceRecord = new StringBuilder();
for (int j = 0; j < 10; j++) {
attendanceRecord.append(random.nextInt(2)); // 0或1表示未出勤或出勤
}
attendanceCount.put(studentId, countAttendance(attendanceRecord.toString())); // 把出勤次数存入Map
}
// 对出勤次数和学号进行排序
List<Map.Entry<String, Integer>> sortedList = new ArrayList<>(attendanceCount.entrySet());
Collections.sort(sortedList, (o1, o2) -> {
// 先按出勤次数降序排列
int compareResult = o2.getValue().compareTo(o1.getValue());
if (compareResult == 0) {
// 如果出勤次数相同,按学号从小到大排列
compareResult = o1.getKey().compareTo(o2.getKey());
}
return compareResult;
});
// 输出结果
for (Map.Entry<String, Integer> entry : sortedList) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
// 计算出勤次数
private static int countAttendance(String attendanceRecord) {
int count = 0;
for (int i = 0; i < attendanceRecord.length(); i++) {
if (attendanceRecord.charAt(i) == '1') {
count++;
}
}
return count;
}
}
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)