Java中如何查找多数组最大总分并返回对应首索引的玩家名称
实现方法
你只需要新增两个变量记录当前最高得分和对应玩家姓名,在遍历每个玩家得分时更新这两个变量,最后输出即可,修改步骤如下:
- 第一步:在统计玩家数的
gamerCount变量下方,新增两个变量存储最高得分和对应玩家名
int maxScore = Integer.MIN_VALUE; String topGamer = "";
- 第二步:在while循环中,每计算完当前玩家的总分
sum后,新增判断逻辑更新最高得分记录
// 原有代码 System.out.println(sum); gamerCount++; // 新增逻辑 if (sum > maxScore) { maxScore = sum; topGamer = list[0]; }
- 第三步:修改最后输出Top Gamer的代码,把记录的最高分玩家名拼接进去
// 原有代码修改为 System.out.println("Top Gamer: " + topGamer);
完整修改后的代码
public static void main(String[] args) throws IOException { // 注意Java路径的反斜杠需要转义,原路径要改成双反斜杠 File gameScores = new File("C:\\Users\\jaret\\OneDrive\\Desktop\\GameScores.csv"); if (gameScores.exists()) { BufferedReader br = null; String line = ""; String csvSplitBy = ","; int gamerCount = 0; // 新增的最高得分记录变量 int maxScore = Integer.MIN_VALUE; String topGamer = ""; br = new BufferedReader(new FileReader(gameScores)); System.out.println("----------------------------------------------------------"); System.out.println("-------------------------------------"); System.out.println("Games Report"); System.out.println("----------------------------------------------------------"); System.out.println("-------------------------------------"); System.out.println("Gamer 1 2 3 4 5 6 7"); System.out.println(" 8 9 10 Total"); System.out.println("----------------------------------------------------------"); System.out.println("-------------------------------------"); while ((line = br.readLine()) != null) { // 原代码这里的new String[10]无意义,会被split结果覆盖,可直接简化定义 String list[] = line.split(csvSplitBy); int sum = 0; for (String element : list) { try { Integer num = Integer.parseInt(element); sum += num; } catch (NumberFormatException nfe) { System.out.print(list[0] + " " + list[1] + (list[1].length() > 10 ? " " : " ") + list[2] + (list[2].length() > 10 ? " " : " ") + list[3] + (list[3].length() > 10 ? " " : " ") + list[4] + (list[4].length() > 10 ? " " : " ") + list[5] + (list[5].length() > 10 ? " " : " ") + list[6] + (list[6].length() > 10 ? " " : " ") + list[7] + (list[7].length() > 10 ? "\n " : "\n ") + list[8] + (list[8].length() > 10 ? " " : " ") + list[9] + (list[9].length() > 10 ? " " : " ") + list[10] + " "); } } System.out.println(sum); gamerCount++; // 新增的更新最高得分逻辑 if (sum > maxScore) { maxScore = sum; topGamer = list[0]; } } System.out.println("----------------------------------------------------------"); System.out.println("-------------------------------------"); System.out.println("# of Gamers: " + gamerCount); // 修改后的输出 System.out.println("Top Gamer: " + topGamer); br.close(); } String newGamer; newGamer = userInput(); enterGamer(newGamer); }
效果说明
你提供的测试数据中最高得分玩家为Adelie,修改后输出的Top Gamer行将自动显示为Top Gamer: Adelie,如果后续csv文件数据更新,也会自动识别最新的最高分玩家。
内容的提问来源于stack exchange,提问作者Jaret Daly
相关产品推荐
相关产品推荐

