You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java数组处理异常:最高分最低分输出错误及数据篡改问题

问题排查与修复方案

问题根源

你的代码核心问题出在highestLowest()方法中:你错误地直接修改了原始grade数组的元素值,而非更新最高分/最低分对应的索引位置。

具体来说:

  • 当发现grade[i]比当前grade[max_index]高时,你执行了grade[max_index] = grade[i];,这会把数组第一个位置(初始max_index=0)的成绩替换成当前遍历到的高分,导致原始学生成绩被篡改。
  • 同时,max_index和min_index始终保持初始值0,所以最终输出的最高分和最低分都会指向第一个学生,且原始成绩数组已经被破坏。

修复方案

修改highestLowest()方法,只更新索引值,不修改原始成绩数组:

public static void highestLowest (){
    int max_index = 0;
    int min_index = 0;
    
    // Loop from index 0 to count of arrays
    for(int i=0; i<count; i++)
    {
        // Check for the index of max grade
        if(grade[i] > grade[max_index])
            max_index = i; // 更新为当前最高分的索引,而非修改数组值
        // Check for the index of min grade
        if(grade[i] < grade[min_index])
            min_index = i; // 更新为当前最低分的索引,而非修改数组值
    }
    
    System.out.println("Highest : " + name[max_index] + ", " + grade[max_index]);
    System.out.println("Lowest : " + name[min_index] + ", " + grade[min_index]);
}

修复效果说明

  1. 原始grade数组不会再被篡改,showAllStudents()将正确输出学生的初始成绩:
    1. Doyoung - 50 - FAILED
    2. Ramburat - 100 - PASSED
    
  2. highestLowest()将正确输出最高分和最低分:
    Highest : Ramburat, 100
    Lowest : Doyoung, 50
    

内容的提问来源于stack exchange,提问作者meorasso

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 07:35:22