比较Java中的两个整数数组

2022-01-25 00:00:00 arrays compare java

我正在尝试编写代码来比较两个数组.在第一个数组中我放了自己的数字,但第二个数组从输入文件中获取数字.此数组的大小由文件中的第一个数字决定,而第一个数组的大小始终为 10.两个数组的长度必须相同,数字也必须相同.

I am trying to write code to compare two arrays. In the first array I have put my own digits, but the second the array takes numbers from the input file. The size of this array is determined by the first number in the file while the first array is always of size 10. The length must be the same for both arrays as well as the numbers.

我的代码如下:

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;
            }
        }
    }       
}

推荐答案

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

相关文章