在数组中查找最小值和最大值 [英] Finding a minimum and maximum value in an array

查看:129
本文介绍了在数组中查找最小值和最大值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我正在尝试查找用户放入的数组的最小值和最大值.

So I'm trying to find a min and max of an array which are put in by the user.

这是我的代码

public static void main(String[] args) {

    int[] a = new int[args.length];
    for (int i = 0; i < args.length; i++) {
        a[i] = Integer.parseInt(args[i]);
        int max = a[0];
        for (int j = 1; j < args.length; j++) {
            if (a[j] > max) {
                max = a[j];
            }
        } 
        System.out.println("the maximum value of the array is " + max);
    }
}

但是我得到的输出是我输入的每个数字.这里的错误是什么?

But the output I am getting is every single number I have put in. What is my mistake here?

推荐答案

让我们完成该过程.由于这是一个int数组,因此将值初始化为0.在第一个for循环中,我们将第一个int分配给a[0].然后在第二个for循环中,我们检查数组中的每个值是否都是最大值(因此将第一个值与零负载进行比较),然后退出嵌套的for循环并打印语句(值为a[0],如果这是积极的.)

Let's go through the process. Because this is an int array the values are initialized to 0. In the first for loop we assign the first int to a[0]. Then in the second for loop we check every value in the array if it is maximal (so checking the first value against a load of zeros) then you exit the nested for loop and print the statement (with the value of a[0], if it was positive).

现在,我们经历外循环的第二个循环,如果再次增大该值,则将打印该值,否则将重新打印第一个值(您的数组是否有可能升序排列?),依此类推值.

Now we go through the second cycle of the outer loop, if this was bigger again this value will be printed, otherwise the first value will be reprinted (was your array in ascending order by any chance?) and so on for each value.

如前所述,一个循环就足够了,并确保您的print语句在外部for循环之外

As was commented, a single loop would be enough, and ensure your print statement is outside of the outer for loop

希望这会有所帮助

这篇关于在数组中查找最小值和最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆