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

Java将数组传入三个方法求平均、最值 输出异常问题求助

问题原因分析
  • 重复输出中间结果:三个计算方法的调用被写在了元素输入的循环体内,每成功录入一个元素就会触发一次计算打印,因此会多次输出中间结果。
  • 最小值为0且极值打印逻辑混乱:Java int数组初始化后未手动赋值的元素默认值为0,未完成所有元素录入就调用计算方法时,会读到数组中默认的0值导致最小值计算错误;同时原有极值计算方法将打印语句写在了遍历比较的条件分支内,只有找到更大/更小值时才会打印,不符合最终仅输出一次结果的需求。
修正方案
  • 将三个计算方法的调用移到元素输入循环的外侧,等所有元素全部录入完成后再统一调用计算
  • 调整三个方法内的打印逻辑,移除遍历过程中的打印语句,统一在计算出最终结果后打印一次
修正后完整代码
package arrays;
import java.util.Scanner;
public class AssignmentArrays {

    public static void main (String[] args) {
        Scanner inputs = new Scanner(System.in);
      
        System.out.println("Please enter the size of the array: ");
        int size = inputs.nextInt();
     
        int[] Array = new int[size]; 
 
        for (int i = 0; i < size;) {
            System.out.println("Please enter array elements: ");
            int value = inputs.nextInt();
            if (value >=100 || value <=0) {
                System.out.println("Only values greater than 0 and less than 100 can be accepted.");
            } 
            else {
                Array[i] = value;
                i++;
            } 
        }
        // 所有元素录入完成后统一计算打印
        average(Array); 
        getMinValue(Array);
        getMaxValue(Array); 
    } 

    public static int average(int[] Array) {
        int sum = 0;
        for (int i = 0; i < Array.length; i++) {
            sum += Array[i];
        }
        int average = sum / Array.length; 
        System.out.println("The average is " + average + ".");
        return average;
    } 

    public static int getMaxValue(int[] Array) {
        int maxValue = Array[0];
        for (int i = 1; i < Array.length; i++){
            if (Array[i] > maxValue){
                maxValue = Array[i];
            }
        }
        System.out.println("Max Value: " + maxValue);
        return maxValue;
    }

    public static int getMinValue(int[] Array) {
        int minValue = Array[0];
        for (int i = 1; i < Array.length; i++){
            if (Array[i] < minValue) {
                minValue = Array[i];
            }
        }
        System.out.println("Min Value: " + minValue);
        return minValue;
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 07:15:10