第七章第二十七题(相同的数组)(Same array)
-
7.27(相同的数组)如果两个数组list1和list2的内容相同,那么就说他们是相同的。使用下面方法头编写一个方法,如果list1和list2是相同的,该方法就返回true:
public static boolean equals(int[] list1,int[] list2)
编写一个测试程序,提示用户输入两个整数列表,然后显示他们两个是否相同。下面是运行示例。注意,输入的第一个数字列表中元素的个数。该数字不是列表的一部分。
Enter list1:5 5 5 6 6 1
Enter list2:5 2 5 6 1 6
two lists are not identical
Enter list1:5 2 5 6 6 1
Enter list2:5 5 2 6 1 6
Two lists are identical
7.27(Same array)If the contents of two arrays LIST1 and List2 are the same, they are said to be the same. Write a method using the following method header. If LIST1 and List2 are the same, the method returns true:
public static boolean equals(int[] list1,int[] list2)
Write a test program, prompt the user to enter two integer lists, and then display whether they are the same. Here is a running example. Notice the number of elements in the first numeric list you enter. The number is not part of the list.
Enter list1:5 5 5 6 6 1
Enter list2:5 2 5 6 1 6
two lists are not identical
Enter list1:5 2 5 6 6 1
Enter list2:5 5 2 6 1 6
Two lists are identical -
参考代码:
package chapter07; import java.util.Arrays; import java.util.Scanner; public class Code_27 { public static void main(String[] args) { Scanner input=new Scanner(System.in); System.out.print("Enter list1:"); int length1=input.nextInt(); int[] list1=new int[length1]; for(int i=0;i<list1.length;i++){ list1[i]=input.nextInt(); } System.out.print("Enter list2:"); int length2=input.nextInt(); int[] list2=new int[length2]; for(int i=0;i<list2.length;i++){ list2[i]=input.nextInt(); } if(equals(list1,list2)){ System.out.println("Two lists are identical"); } else System.out.println("TWo lists are not identical"); } public static boolean equals(int[] list1,int[] list2){ if(list1.length!=list2.length) return false; 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:5 2 5 6 6 1 Enter list2:5 5 2 6 1 6 Two lists are identical Process finished with exit code 0