第八章第二十九题(相等的数组)(equal array)
-
8.29(相等的数组)如果两个二维数组m1和m2具有相同的内容,则认为它们是相同的。编写一个方法,如果m1和m2是相同的话,返回true。使用下面的方法头:
public static boolean equals(int[][] m1,int[][] m2)
编写一个测试程序,提示用户输入了两个3x3的整数数组。显示两个矩阵是否是严格相同的。下面是一个运行示例:
Enter list1:51 22 25 6 1 4 24 54 6
Enter list2:51 25 22 6 1 4 24 54 6
The two arrays are identical
8.29(equal array)Two two dimensional arrays M1 and M2 are considered identical if they have the same content. Write a method that returns true if M1 and M2 are the same. Use the following method header:
public static boolean equals(int[][] m1,int[][] m2)
Write a test program to prompt the user to input two 3x3 integer arrays. Shows whether the two matrices are exactly the same. Here is a running example:
Enter list1:51 22 25 6 1 4 24 54 6
Enter list2:51 25 22 6 1 4 24 54 6
The two arrays are identical -
参考代码:
package chapter08; import java.util.Arrays; import java.util.Scanner; public class Code_29 { public static void main(String[] args) { Scanner input=new Scanner(System.in); System.out.print("Enter list1:"); int[][] list1=new int[3][3]; for(int i=0;i<list1.length;i++){ for(int j=0;j<list1[i].length;j++){ list1[i][j]=input.nextInt(); } } System.out.print("\nEnter list2:"); int[][] list2=new int[3][3]; for(int i=0;i<list2.length;i++){ for(int j=0;j<list2[i].length;j++){ list2[i][j]=input.nextInt(); } } if (equals(list1,list2)) System.out.println("The two arrays are identical"); else System.out.println("The two arrays are not identical"); } public static boolean equals(int[][] m1,int[][] m2){ int[] list1=new int[m1.length*m1[0].length]; int[] list2=new int[m2.length*m2[0].length]; int k=0; for(int i=0;i<m1.length;i++){ for(int j=0;j<m1[i].length;j++){ list1[k]=m1[i][j]; k++; } } k=0; for(int i=0;i<m1.length;i++){ for(int j=0;j<m1[i].length;j++){ list2[k]=m2[i][j]; k++; } } Arrays.sort(list1); Arrays.sort(list2); for(int i=0;i<list1.length;i++){ if (list1[i]!=list2[i]) return false; } return true; } }
-
结果显示:
Enter list1:51 22 25 6 1 4 24 54 6 Enter list2:51 25 22 6 1 4 24 54 6 The two arrays are identical Process finished with exit code 0