Java遍历分数数组取最大值索引匹配队名输出异常求解
问题排查与修复方案
你的代码存在3个直接导致分数、队名匹配错乱的核心问题,逐个修复即可解决异常:
核心Bug说明
- 最高分方法逻辑缺陷
Java基本类型是值传递,你把main方法里的highIndex作为参数传入highScore()时,方法内部修改的是参数的临时副本,不会改变main方法里的原始变量值。且你在输出语句中反复调用3次highScore()做索引取值,属于无意义的重复计算,还会增加异常概率。另外highScore()方法不需要额外传入索引参数,索引初始值完全可以在方法内部定义。 - 最低分方法破坏数组索引对应关系
你在lowScore()中调用的Arrays.sort(teamScores)会直接修改传入的原始数组的元素顺序,排序后teamScores的元素位置和teamNames的索引绑定关系完全被打乱,这就是你反复出现“分数对时队名错、队名对时分数错”的根本原因。 - 输入流读取逻辑错误
你为同一个输入流创建了两个独立的Scanner对象,且nextInt()方法读取整数后不会消费行尾的换行符,会导致第一次读取队名时直接读到空字符串,后续所有队名的存储位置整体偏移,和分数的索引无法对应。
修复约束对齐
- 保留
teamScores、teamNames两个独立数组,不做合并 - 最高分查找保留for循环遍历逻辑,不使用排序实现
- 修复最低分方法,去掉会修改原数组的排序逻辑,同样用for循环遍历找最小值,避免破坏两个数组的索引对应关系
修复后完整代码
import java.util.Scanner; public class SmithJustin_Asgn6 { // 去掉多余的highIndex传参,方法内部初始化索引初始值 public static int highScore(int[] teamScores) { int max = teamScores[0]; int highIndex = 0; for(int i = 1; i < teamScores.length; i++) { if(max < teamScores[i]) { max = teamScores[i]; highIndex = i; } } return highIndex; } // 重写lowScore,禁止修改原数组,用遍历方式找最小值 public static int lowScore(int[] teamScores) { int min = teamScores[0]; for(int i = 1; i < teamScores.length; i++) { if(min > teamScores[i]) { min = teamScores[i]; } } return min; } public static void main(String[] args) { // 只保留一个Scanner对象,避免输入流冲突 Scanner sc = new Scanner(System.in); System.out.print("Enter the number of teams would you like to enter data for: "); int teams = sc.nextInt(); // 消费nextInt遗留的换行符 sc.nextLine(); int [] teamScores = new int[teams]; String [] teamNames = new String[teams]; for(int i = 0; i < teams; i++) { System.out.println("\nTeam "+ i +":\n"); System.out.print("Enter Team's name: "); String teamName = sc.nextLine(); teamNames[i] = teamName; System.out.print("Enter Team's score (400-1000): "); int teamScore = sc.nextInt(); teamScores[i] = teamScore; System.out.println(); // 消费每次读分数遗留的换行符 sc.nextLine(); } // 只调用一次方法拿到最高分索引,避免重复计算 int maxIndex = highScore(teamScores); int highestScore = teamScores[maxIndex]; String highestTeam = teamNames[maxIndex]; int lowestScore = lowScore(teamScores); System.out.println(); System.out.println("The high score is "+ highestScore +" by team " + highestTeam + " and the low score is "+ lowestScore +"."); sc.close(); } }
内容的提问来源于stack exchange,提问作者Justin Smith
相关产品推荐
相关产品推荐

