Q12. Write a method named equals that accepts two arrays of integers as parameters and returns true if they contain exactly the same elements in the same order, and false otherwise. Note that the arrays might not be the same length; if the lengths differ, return false. Do not call Arrays.equals in your solution. For example, if the following arrays are declared:
int[] a1 = {10, 20, 30, 40, 50, 60}; int[] a2 = {10, 20, 30, 40, 50, 60}; int[] a3 = {20, 3, 50, 10, 68}; The call equals(a1, a2) returns true but the call equals(a1, a3) returns false. *
import java.util.*; import java.util.Scanner; public class Q12 { //数组相等判断可以用Array.equlas( public static void main(String[] args) { // TODO Auto-generated method stub Scanner console = new Scanner (System.in); /*System.out.println("Type the length for array a1: "); int length = console.nextInt(); System.out.println("Type the length for array a2: "); int length1 = console.nextInt(); System.out.println("Type the length for array a3: "); int length2 = console.nextInt();*/ //定义三个长度为length length1的数组 int []a1 = {10,20,30,40,50,60}; int []a2 = {10,20,30,40,50,60}; int []a3 = {20,3,50,60}; //样本数组输入 /* int []a1 = new int [length]; int []a2 = new int [length1]; int []a3 = new int [length2]; for (int i=0;i<a1.length;i++) { System.out.println("Type the #"+(i+1)+" for a1"); a1[i]=console.nextInt(); } for (int a=0;a<a2.length;a++) { System.out.println("Type the #"+(a+1)+" for a2"); a2[a]=console.nextInt(); } for (int c=0;c<a3.length;c++) { System.out.println("Type the #"+(c+1)+" for a3"); a2[c]=console.nextInt(); }*/ //定义数组 boolean result = equals(a1,a2); System.out.println("The call of(a1,a2)is: "+result); result = equals(a2,a3); System.out.println("The call of(a2,a3)is: "+result); result = equals(a1,a3); System.out.println("The call of(a1,a3)is: "+result); } public static boolean equals (int[]num,int[]num1) { boolean result; if (num.length!=num1.length) { result = false; }else { result = true; for (int i=0;i<num.length;i++) { if(num[i]!=num1[i]) { result = false; //最好用if/for从句 或while从句/i++/条件判读 } } } return result; } }