比较 Java 中的两个整数数组 [英] Comparing two integer arrays in Java

查看:42
本文介绍了比较 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);
    }

这篇关于比较 Java 中的两个整数数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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