#第七章第二十六题(完全相同的数组)(Exactly the same array)
-
7.26(完全相同的数组)如果两个数组list1和list2对应的元素相等,那么认为list1和list2是完全相同的。使用下面的方法头编写一个方法,如果list1和list2完全相同,则返回true:
public static boolean equals(int[] list1, int[] list2)
编写一个测试程序,提示用户输入两个整数列表,然后显示这两个列表是否完全相同。下面是运行示例。注意,输入的第一个数字表明列表中的元素的个数。该数字不是列表的一部分。
Enter list1 size and contents:5 2 5 6 1 6
Enter list1 size and contents:5 2 5 6 1 6
Two lists are strictly identical
Enter list1 size and contents:5 2 5 6 6 1
Enter list1 size and contents:5 2 5 6 1 6
Two lists are not strictly identical
7.26(Exactly the same array)If the elements corresponding to two arrays LIST1 and List2 are equal, LIST1 and List2 are considered identical. Write a method using the following method header, and return true if LIST1 and List2 are identical:
public static boolean equals(int[] list1, int[] list2)
Write a test program, prompt the user to enter two integer lists, and then show whether the two lists are identical. Here is a running example. Note that the first number you enter indicates the number of elements in the list. The number is not part of the list.
Enter list1 size and contents:5 2 5 6 1 6
Enter list1 size and contents:5 2 5 6 1 6
Two lists are strictly identical
Enter list1 size and contents:5 2 5 6 6 1
Enter list1 size and contents:5 2 5 6 1 6
Two lists are not strictly identical -
参考代码:
package chapter07; import java.util.Scanner; public class Code_26 { public static void main(String[] args){ int[] nums1 = new int[10]; int[] nums2 = new int[10]; Scanner cin = new Scanner(System.in); System.out.print("Enter list1 size and contents:"); int number1 = cin.nextInt(); for(int i = 0; i < number1; ++i){ nums1[i] = cin.nextInt(); } System.out.print("Enter list1 size and contents:"); int number2 = cin.nextInt(); for(int i = 0; i < number2; ++i){ nums2[i] = cin.nextInt(); } if (equals(nums1,nums2)) System.out.println("Two lists are strictly identical"); else System.out.println("Two lists are not strictly identical"); } public static boolean equals(int[] list1, int[] list2){ for(int i = 0; i < list1.length; ++i){ if(list1[i] != list2[i]) return false; } return true; } }
-
结果显示:
Enter list1 size and contents:5 2 5 6 1 6 Enter list1 size and contents:5 2 5 6 1 6 Two lists are strictly identical