user2052514 user2052514 - 2 months ago 12
Java Question

Comparing two integer arrays in java

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. My code is below:

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

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