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

Java使用Scanner类输入数组查找最值时最小值总返回0问题咨询

问题排查

  • 初始化min、max时机错误:你创建int数组后未赋值就直接取myArray[0]作为初始最值,Java中int数组默认初始值全为0,若用户输入的所有数值都大于0,min会一直保留初始的0,导致结果错误。
  • 判断逻辑不合理:使用else if判断最值是错误的,min和max的判断相互独立,若某一输入值同时小于当前min且大于当前max(这种场景在初始最值设置错误时很容易出现),else if会跳过max的判断。

修正方案

推荐将初始最值设置为int类型的极值,避免提前读取元素的额外操作,修正后的代码如下:

import java.util.Arrays;
import java.util.Scanner;

public class Loops {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        System.out.print("How many numbers in a set: ");
        int number = scan.nextInt();
        int[] myArray = new int[number];
        // 初始最值设置为int类型的极值
        int min = Integer.MAX_VALUE;
        int max = Integer.MIN_VALUE;
        
        System.out.println("Input your numbers: ");
        for(int i = 0; i < myArray.length; i++) {
            myArray[i] = scan.nextInt();
            // 两个判断分开写,不要用else if
            if (myArray[i] < min) {
                min = myArray[i];
            }
            if (myArray[i] > max) {
                max = myArray[i];
            }
        }
        System.out.println(Arrays.toString(myArray));
        System.out.println(max + " " + min);
        System.out.println();
        scan.close();
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 12:54:03