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

Java数组去重程序添加do while哨兵法后二次输入崩溃求助

Java数组唯一值提取程序循环崩溃问题排查

问题根源

  • 全局静态变量n未在每次循环时重置。第一次运行后n记录了当前唯一值的数量,第二次调用getDistinct方法时,n会从之前的数值继续累加,当n达到10时,finalArray[n++]会访问数组索引10(数组长度仅为10,合法索引是0-9),触发ArrayIndexOutOfBoundsException导致程序崩溃。
  • 同时打印唯一值的循环依赖这个全局n,第二次循环时n是两次运行的累计值,会输出错误内容。

修复思路

  1. 移除全局静态变量n,改用方法内的局部变量维护唯一值计数,避免状态残留。
  2. 返回裁剪后的有效唯一值数组,确保打印逻辑准确。

修复后的完整代码

import java.util.Scanner;

public class DistinctValuesCourtney {

    public static void main(String[] args) {
        int[] array = new int[10];
        Scanner input = new Scanner(System.in);
        char doAgain;
    
        do {
            System.out.print("Please enter 10 integers for the array:");  
            // 读取输入填充数组
            for (int i = 0; i < array.length; i++) {
                array[i] = input.nextInt(); 
            }
            
            // 获取去重后的数组
            int[] distinctValues = getDistinct(array);
            
            // 打印结果
            System.out.print("Distinct values you entered: ");
            for (int value : distinctValues) {
                System.out.print(value + " ");
            }
            System.out.println();
            
            // 询问是否继续
            System.out.println("Would you like to retry? Y/N: ");   
            doAgain = input.next().charAt(0);
        } while ((doAgain == 'Y') || (doAgain == 'y'));
        
        System.out.println("Have a nice day!");
        input.close(); // 关闭输入流释放资源
    }
    
    public static int[] getDistinct(int[] inputArray) {       
        int[] tempStorage = new int[inputArray.length];
        int uniqueCount = 0;
                
        for (int num : inputArray) {
            boolean isDuplicate = false;
            // 检查当前数字是否已经在已记录的唯一值中
            for (int j = 0; j < uniqueCount; j++) {
                if (num == tempStorage[j]) {
                    isDuplicate = true;
                    break;
                }
            }
            if (!isDuplicate) {
                tempStorage[uniqueCount++] = num;    
            }
        }
        // 裁剪数组,只保留有效唯一值部分
        int[] result = new int[uniqueCount];
        System.arraycopy(tempStorage, 0, result, 0, uniqueCount);
        return result;
    }
}

额外优化说明

  • 用局部变量uniqueCount替代全局静态变量,彻底避免跨调用的状态污染。
  • 最终返回的数组是刚好容纳唯一值的长度,不会有多余的默认0值。
  • 关闭Scanner资源,避免潜在的资源泄漏问题。
  • 代码逻辑更直观,可读性更强。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 14:50:37