简体   繁体   English

如何比较嵌套数组中的数字

[英]How do I compare numbers in a nested array

For example if I have a two dimensional array that looks like: 例如,如果我有一个二维数组,如下所示:

10 2 5 4 10 2 5 4

6 3 7 8 6 3 7 8

How would I be able to check if each element is larger than each other? 我如何能够检查每个元素是否大于彼此? In this case I would get 10 > 2, 5 > 4, and 6 > 3. 在这种情况下,我将得到10> 2、5> 4和6> 3。

If I am not not wrong you need code which would compare odd matrix position with even . 如果我没有记错的话,您需要将奇数矩阵位置与偶数位置进行比较的代码。 Kindly find below code which would be adequate for your goal. 请在下面找到适合您目标的代码。

public class Sample {

    public static void main(String[] args) {

        int[][] a = {{2,3,4,5},{16,12,3,6}};

        for(int j=0;j<a.length;j++)
        {
            int i=0;
            while(i<a[j].length && i+1 < a[j].length)
            {
                if(a[j][i] > a[j][i+1])
                {
                    System.out.println(a[j][i] +" is Greater than "+a[j][i+1] );
                }
                else
                {
                    System.out.println(a[j][i] +" is Lesser than "+a[j][i+1] );
                }
                i=i+2;
            }
        }
    }

}

Hope this was helpful. 希望这会有所帮助。

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

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