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

Java数组求最值异常:最小值返回0,求解决及最值索引获取方法

问题分析与解决方案

一、最小值始终返回0的原因及修复

你的代码里,int min = array[0];这行存在逻辑漏洞:Java中新建的int数组元素默认值为0,而你在还未输入任何元素时就将array[0]赋值给了min。如果输入的所有数字都大于0,循环里的else if (array[i]<min)条件永远不会触发(输入的数都比0大),导致min一直保留初始的0值。

修复方案

把min和max的初始化逻辑调整到第一个元素输入之后,或者在循环内处理第一次迭代的情况:

修改后的核心逻辑:

int array[] = new int[in];
int min, max;
int maxIndex = 0, minIndex = 0;

for (int i=0; i < in; i++){
    System.out.print("Input number "+(i+1)+" :");
    array[i]=sc.nextInt();
    // 第一次输入时直接赋值min和max
    if(i == 0){
        min = array[i];
        max = array[i];
    } else {
        if(array[i]>max){
            max = array[i];
            maxIndex = i;
        }
        // 这里不要用else if,避免同时满足大小条件时漏判
        if(array[i]<min){
            min = array[i];
            minIndex = i;
        }
    }                
}

二、获取并打印最大值、最小值的索引

额外定义maxIndex和minIndex变量存储对应索引,在更新max或min的同时同步更新这两个变量即可。

完整修改后的代码

import java.util.Scanner;

public class App {
    public static void main(String[] args) {

        int in;

        Scanner sc = new Scanner(System.in);
        System.out.print("Enter the number of elements you want to store: ");
        in=sc.nextInt();  

        int array[] = new int[in];
        int min, max;
        int maxIndex = 0, minIndex = 0;

        for (int i=0; i < in; i++){
            System.out.print("Input number "+(i+1)+" :");
            array[i]=sc.nextInt();
            if(i == 0){
                min = array[i];
                max = array[i];
            } else {
                if(array[i]>max){
                    max = array[i];
                    maxIndex = i;
                }
                if(array[i]<min){
                    min = array[i];
                    minIndex = i;
                }                
            }
        }
        sc.close();

        System.out.print(" The inputed array is "); 
        for (int i=0; i < in; i++){  
            System.out.print(array[i]+" ");
        }
        System.out.println("\n    --------------------");
        System.out.println("The highest number is: "+max + ",对应的索引是:" + maxIndex);
        System.out.println("The lowest number is: "+ min + ",对应的索引是:" + minIndex);
    }  
}

补充说明

  • 索引默认从0开始,如果需要显示从1开始的位置,打印时将索引值加1即可,比如maxIndex + 1。
  • 若数组中有多个相同的最大值/最小值,上述代码会记录最后一个出现的对应索引;如果需要记录第一个出现的,将判断条件改为array[i] >= max(最大值)或array[i] <= min(最小值)即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 09:15:59