检查两个数组在相同位置是否具有相同的值

时间:2016-04-18 23:40:56

标签: java arrays

我正在编写使用数组作为拼图的一部分的代码,拼图的目标是拼图,用户必须输入命令才能将拼图恢复原状。我已将原始文件保存在变量中,并将当前文件保存在用户输入更改的变量中。

如果用户完成拼图,我希望while循环终止,所以我尝试了以下代码:

if (arroriginal == currentarr){
            System.out.println("Congratulations! You have completed the puzzle");
        }

但这并不起作用,因为当我开始拼图时,任何输入都会导致完成消息。谁能帮我?? :-)

我猜测'=='运算符只是检查内容而不是数组中值的位置

4 个答案:

答案 0 :(得分:0)

使用Arrays.equals(array1, array2)比较数组的内容

array1 == array2只有在相同的情况下才会返回true。

public static void main(String[] args) throws Exception {
    int [] array1 = new int[]{1,2,3};
    int [] array2 = new int[]{1,2,3};
    int [] array3 = new int[]{1,2,3};

    System.out.println(array1 == array2);//this will print false
    System.out.println(Arrays.equals(array1, array2));//this will print true
    array2 = array1;
    //now "==" will return true
    System.out.println(array1 == array2);
    Arrays.sort(array1);
    Arrays.sort(array3);
    System.out.println(Arrays.equals(array1,array3));//this will return true
}

以下是demo

答案 1 :(得分:0)

假设

int a = new a[5];
int b = new b[5];

这是两个带有一些值的数组 首先,你必须对数组进行排序,以确定如何使位置相同

for(i=0;i<5;i++){
if(a[i]!=b[i]){
//print arrays don't match
//use some flag that helps u to know that it's a failure
break;   // u have to use break statement to end the loop
}
}
//Now use the flag here using if statement to find if u have a match or not

从你的问题中寻找......这是我得到的......希望它有所帮助...

答案 2 :(得分:0)

替代方案,另一方面效率较低的方法。使用它的唯一原因是你要比较不同长度的数组。

int array1[];
int array2[];

boolean flag = true;
int size;
if(array1.length > array2.length) size = array2.length;
else size = array1.length;  
    for(int i = 0; i < size; i++) {
        if(array1[i] != array2[i]) {
            break;
            flag = false;
        }
    }
if(flag == false) System.out.print("Not equal!");

这基本上可以确定哪个数组较大,然后循环较小数组的大小,并检查每个元素以查看它们是否相等。如果没有,它标记为false并打破循环。

答案 3 :(得分:-1)

您还可以遍历数组中的值并退出循环,找到不同的值。