比较Java中的两个整数数组

我正在尝试编写代码以比较两个数组。在第一个数组中,我输入了自己的数字,但是在第二个数组中,输入了输入文件中的数字。该数组的大小由文件中的第一个数字确定,而第一个数组的大小始终为10。两个数组和数字的长度必须相同。我的代码如下:


public static void compareArrays(int[] array1, int[] array2) {

    boolean b = false;

    for (int i = 0; i < array2.length; i++) {


        for (int a = 0; a < array1.length; a++) {


            if (array2[i] == array1[a]) {

                b = true;

                System.out.println("true");

            } else {

                b = false;

                System.out.println("False");

                break;

            }

        }

    }       

}


LEATH
浏览 693回答 3
3回答

九州编程

public static void compareArrays(int[] array1, int[] array2) {&nbsp; &nbsp; &nbsp; &nbsp; boolean b = true;&nbsp; &nbsp; &nbsp; &nbsp; if (array1 != null && array2 != null){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (array1.length != array2.length)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; b = false;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; else&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for (int i = 0; i < array2.length; i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (array2[i] != array1[i]) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; b = false;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }else{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; b = false;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(b);&nbsp; &nbsp; }

慕少森

使用Arrays.equals(ary1,ary2); //返回布尔值编辑您可以使用Arrays.deepEquals(ary1,ary2)比较二维数组以及还要检查此链接以了解Arrays.equls(ar1,ar2)和之间的比较Arrays.deepEquals(ar1,ar2)Java Arrays.equals()对于二维数组返回false编辑2,如果您不想使用这些库方法,则可以像下面这样轻松实现您的方法:public static boolean ArrayCompare(int[] a, int[] a2) {&nbsp; &nbsp; if (a==a2)&nbsp; &nbsp;// checks for same array reference&nbsp; &nbsp; &nbsp; &nbsp; return true;&nbsp; &nbsp; if (a==null || a2==null)&nbsp; // checks for null arrays&nbsp; &nbsp; &nbsp; &nbsp; return false;&nbsp; &nbsp; int length = a.length;&nbsp; &nbsp; if (a2.length != length)&nbsp; // arrays should be of equal length&nbsp; &nbsp; &nbsp; &nbsp; return false;&nbsp; &nbsp; for (int i=0; i<length; i++)&nbsp; // compare array values&nbsp; &nbsp; &nbsp; &nbsp; if (a[i] != a2[i])&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return false;&nbsp; &nbsp; return true;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java