简体   繁体   English

如何显示数组的最小和最大元素?

[英]How to display the min and max elements of an array?

I've been trying to solve this problem for quite some time now.我已经尝试解决这个问题已有一段时间了。 I'm trying to display the min and max elements of an array, but the min always remains at 0. Here's the code that explains my issue:我正在尝试显示数组的最小和最大元素,但最小值始终保持为 0。这是解释我的问题的代码:

public class ArrExs {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("enter the array capacity (min 1, max 20): ");
        int n = input.nextInt();
        while(n <= 0 || n > 20) {
            System.out.print("enter a valid number and try again: ");
            n = input.nextInt();
        }
        int[] nums = new int[n];
        maxAndMin(nums);
    }
    public static void maxAndMin(int[] numbers) {
        Scanner input = new Scanner(System.in);
        System.out.println("enter your array elements: ");
        int min = numbers[0];
        int max = numbers[0];
        for(int i = 0; i < numbers.length; i++) {
            numbers[i] = input.nextInt();
            max = (numbers[i] > max) ? numbers[i] : max;
            min = (numbers[i] < min) ? numbers[i] : min;
        }
        System.out.print("min = " + min + ", max = " + max);
    }
}

The output: output:

enter the array capacity (min 1, max 20): 3
enter your array elements: 
2
3
4
min = 0, max = 4

The min always remains at 0, I've tried to edit the code multiple times but I get the same result.最小值始终保持为 0,我尝试多次编辑代码,但得到的结果相同。

I've encountered this problem before and watched a video where the instructor's logic is to set the "Min" and "Max" to the first number entered by the user.我以前遇到过这个问题,看过一个视频,讲师的逻辑是将“Min”和“Max”设置为用户输入的第一个数字。 Then there comes the relational operator to decide which is minimum and maximum.然后是关系运算符来决定哪个是最小值和最大值。

The problem is on the line where you do int min = numbers[0];问题出在你执行int min = numbers[0];的那一行because numbers is an empty array (all of the values are 0).因为numbers是一个空数组(所有值都是 0)。 Since min starts at 0 and nothing in the array is less than 0 then min will remain 0 forever.由于min从 0 开始并且数组中没有任何内容小于 0,因此 min 将永远保持为 0。

Try making min start as a high value such as int.MaxValue and see if that fixes your problem.尝试让min以高值开始,例如int.MaxValue ,看看是否能解决您的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM