2d数组java中的最小值和最大值 [英] min and max value in 2d array java

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

问题描述

我想输出2d数组的最大值和最小值。 Max运行良好,但是即使数组中没有零,min总是输出零。我将 Math.random()设置为99以防止在数组中获得零的机会更小例。 Heres完整代码:

I want to output max and min value of 2d array. Max works well, but min always outputs zero even when theres no zeros in array.I set Math.random() to 99 to prevent smaller chance to get zero in array for this example. Heres full code:

public class e {

public static void main(String[] args)   {

    int a[][] = new int [5][5];
    int l = a[0][0];
    int m = a[0][0];
    int i,j,r,k;


    for(i=0;i<a.length;i++)                   // 
        for(j=0;j<a[i].length;j++){           // 2d array random number generator
            a[i][j] =(int)(Math.random()*99); //
         }
    for(i=0;i<a.length;i++){               //
        for(j=0;j<a[i].length;j++)         //
                                           // create 2d array and output it
    System.out.print(a[i][j] + "\t");      //   
    System.out.println();                  //

}
    System.out.println("\t"); 
        for(r=0;r<a.length;r++){           //
            for(k=0;k<a.length;k++)        //
                if(a[r][k] < m){           // finds a min value
                    m = a[r][k];           //

            }
        }

    System.out.println("\t");               // 
        for(i=0;i<a.length;i++){            //
            for(j=0;j<a.length;j++)         // finds a max value
                if(a[i][j] > l){            //
                    l = a[i][j];            //

            }
        }
    System.out.println("min value is " + m); //outputs min value
    System.out.println("max value is " + l); // outputs max value
            }
       }


推荐答案

由于您在 a 中选择随机值的方式,将没有小于零的值 - 但也无法保证任何值都将完全为零。但是,您将 m 初始化为零,因为这是数组元素的默认值;没有什么可以小于这个,所以答案总是为零。

Because of the way you choose the random values in a, there will be no value less than zero - but there is also no guarantee that any of the values will be exactly zero. However, you initialize m to be zero, since that is the default value of the array elements; nothing can be smaller than this, so the answer is always zero.

你应该初始化 m = a [0] [0] 紧接在标记为查找最小值的块中启动外部for循环之前,即

You should initialize your m = a[0][0] immediately before you start the outer for loop in the block labelled "finds a min value", i.e.

    m = a[0][0];
    for(r=0;r<a.length;r++){           //
        for(k=0;k<a.length;k++)        //
            if(a[r][k] < m){           // finds a min value
                m = a[r][k];           //

        }
    }

或者,您可以设置 m = Integer.MAX_VALUE (和 l = Integer.MIN_VALUE ),因为这些值保证越来越大分别比他们好。

Alternatively, you can set m = Integer.MAX_VALUE (and l = Integer.MIN_VALUE), since these are guaranteed to have values smaller and larger than them, respectively.

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

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