我在此程序上遇到困难。我必须通过从控制台读取两个数组来比较两个数组,然后在用户输入它们之后,打印一条语句,确定它们是否为真。我不确定是否可以使用compare函数,但是必须使用for循环来完成。
这是我尝试过的:
import java.util.Scanner;
@SuppressWarnings("unused")
public class TwoArrays {
@SuppressWarnings("unused")
public static void main(String[] args) {
Scanner input1 = new Scanner(System.in);
System.out.println("enter the first array");
String firstArrayAsString = input1.nextLine();
System.out.println("enter the second array");
String secondArrayAsString = input1.nextLine();
if (firstArrayAsString. length() != secondArrayAsString.length()){
System.out.println("false.arrays are not equal");
} else {
int arrayLen = firstArrayAsString.length();
char[] firstArray = firstArrayAsString.toCharArray();
char[] secondArray = secondArrayAsString.toCharArray();
int i = 0;
while (i < arrayLen && firstArray[i] == secondArray[i]); {
i++;
}
if (i == arrayLen) {
System.out.println("true.they are equal");
} else {
System.out.println("False.they are not equal");
}
}
input1.close();
}
}
最佳答案
试试这个代码。
char[] firstArray = {'a', 'b', 'c'};
char[] secondArray = {'a', 'b', 'c'};
if (firstArray.length != secondArray.length) {
System.out.println("False.they are not equal");
} else {
boolean isEqual = true;
for (int i = 0; i < firstArray.length; i++) {
if (firstArray[i] != secondArray[i]) {
System.out.println("False.they are not equal");
isEqual = false;
break;
}
}
if (isEqual)
System.out.println("true.they are equal");
}
关于java - 用for循环比较Java中的两个数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26857776/