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

Java计算数组均值中位数众数显示-1、输入no报错逻辑失效问题求助

问题排查与修复说明

核心故障点修复

1. 用户输入no逻辑未触发问题

原始代码中仅将用户输入结果赋值给inputOk变量,未做分支判断,无论用户输入yes/no都会继续执行后续文件读取逻辑。修复方案:用户输入no后直接打印错误提示并退出程序。

inputOk = userInput.equals("yes");
// 新增以下判断
if (!inputOk) {
    System.out.println("ERROR: 用户选择终止程序,运行结束");
    s.close();
    return;
}

2. 中位数、众数返回-1问题

该问题由多个逻辑错误共同导致,逐一修复如下:

  • 有效元素计数错误:main方法中统计有效元素的逻辑写错,错误将数组元素值赋值给计数器,改为计数器自增得到实际有效元素个数n
    // 原始错误代码
    // for (int i=0; i<MAXDATA; i++) {
    //     if (a[i] != -1) {
    //         counter = a[i];
    //     }
    // }
    // 修复后
    int n = 0;
    for (int i=0; i<MAXDATA; i++) {
        if (a[i] != INVALID) {
            n++;
        }
    }
    
  • 中位数逻辑错误:中位数计算要求数组先排序,且要基于有效元素个数计算位置,而非整个数组的最大长度
    // 修复后的calcMedian方法,新增参数n为有效元素个数
    public static double calcMedian(int[] data, int n) {
        // 先对有效元素排序
        Arrays.sort(data, 0, n);
        int middle = n / 2;
        if (n % 2 == 1) {
            return data[middle];
        } else {
            return (data[middle -1] + data[middle]) / 2.0;
        }
    }
    
  • 众数逻辑错误:原始代码遍历整个数组(包含大量无效的-1值),导致-1的出现频率最高被判定为众数,改为仅遍历有效元素
    // 修复后的calcMode方法,新增参数n为有效元素个数
    public static int calcMode(int[] data, int n) {
        int mode = 0, maxCount = 0;
        for (int i = 0; i < n; ++i) {
            int count = 0;
            for (int j = 0; j < n; ++j) {
                if (data[j] == data[i]) {
                    count++;
                }
            }
            if (count > maxCount) {
                maxCount = count;
                mode = data[i];
            }
        }
        return mode;
    }
    
  • 均值精度优化:原始代码用整数除法计算均值会丢失小数位,修改为浮点除法
    // 修复后的calcMean方法,新增参数n为有效元素个数
    public static double calcMean(int[] data, int n) {
        int sum = 0;
        for (int i = 0; i < n; i++) {
            sum += data[i];
        }
        return (double) sum / n;
    }
    

修正后完整代码

package com.company;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Scanner;
import static com.company.ProjectConstants.*;

public class Main {
    public static void main(String[] args) {
        int[] a = new int[MAXDATA];
        boolean fileDone = false;
        boolean inputOk;
        String userInput;
        String theDataFile;

        Scanner s = new Scanner(System.in);
        genProgInfo();

        userInput = s.nextLine();
        userInput = userInput.toLowerCase();

        while (!userInput.equals("yes") && (!userInput.equals("no"))) {
            System.out.println("ERROR: Please input either yes or no: ");
            userInput = s.nextLine();
            userInput = userInput.toLowerCase();
        }

        inputOk = userInput.equals("yes");
        if (!inputOk) {
            System.out.println("ERROR: 用户选择终止程序,运行结束");
            s.close();
            return;
        }

        initDataStorage(a);

        try {
            System.out.println("enter one of the file names:\nData10File.txt\nData30file.txt\nData35file.txt");
            theDataFile = s.next();
            theDataFile = theDataFile.toLowerCase();
            File f = new File(theDataFile);
            Scanner sc = new Scanner(f);

            for (int i = 0; i < MAXDATA; i++) {
                if (sc.hasNext()) {
                    a[i] = sc.nextInt();
                } else {
                    fileDone = true;
                    sc.close();
                    break;
                }
            }

            if (!fileDone) {
                System.out.println("\n\tCAUTION: file has additional data, consider making array larger.");
            }
        } catch (FileNotFoundException e) {
            System.out.println("ERROR: 找不到指定文件");
            e.printStackTrace();
            s.close();
            return;
        }
        s.close();

        // 统计有效元素个数
        int n = 0;
        for (int i=0; i<MAXDATA; i++) {
            if (a[i] != INVALID) {
                n++;
            }
        }
        System.out.println("有效元素个数: "+ n);

        displayResults(calcMean(a,n), calcMedian(a,n), calcMode(a,n));
    }

    public static void initDataStorage(int[] data) {
        for (int i = 0; i < MAXDATA; i++) {
            data[i] = INVALID;
        }
    }

    public static double calcMean(int[] data, int n) {
        int sum = 0;
        for (int i = 0; i < n; i++) {
            sum += data[i];
        }
        return (double) sum / n;
    }

    public static double calcMedian(int[] data, int n) {
        Arrays.sort(data, 0, n);
        int middle = n / 2;
        if (n % 2 == 1) {
            return data[middle];
        } else {
            return (data[middle -1] + data[middle]) / 2.0;
        }
    }

    public static int calcMode(int[] data, int n) {
        int mode = 0, maxCount = 0;
        for (int i = 0; i < n; ++i) {
            int count = 0;
            for (int j = 0; j < n; ++j) {
                if (data[j] == data[i]) {
                    count++;
                }
            }
            if (count > maxCount) {
                maxCount = count;
                mode = data[i];
            }
        }
        return mode;
    }

    public static void genProgInfo() {
        System.out.println("This program will calculate the mean, median, and mode of a number of integers stored in the array");
        System.out.println("Would you like to continue?");
    }

    public static void displayResults(double mean, double median, int mode) {
        System.out.println("mean: " + mean);
        System.out.println("median: " + median);
        System.out.println("mode: " + mode);
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 21:06:04