我已经研究并尝试了几个小时来解决我的问题,但现实是我在上面找不到任何东西。真的很简单。我需要初始化未定义大小的java数组,然后比较两者。在测试我的程序的过程中,当我将数组定义为特定长度时(例如)
int[] array = new int[6];
代码一直等到我输入了六个对象才能进入下一段代码,因为它正在等待定义为数组长度的 6 个整数。但我无法使用定义数组
int[] array = {};
它显然不起作用,因为 array.length 函数将为 0。
我的代码如下。
import java.util.Scanner;
import java.util.Arrays;
public class Test {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
// My problem is in the definition of the arrays or the for loops defining them below.
int[] list1 = new int[]; // undefined
int[] list2 = new int[]; // undefined
// ask user to fill the two arrays to see if they are equal
System.out.print("Enter list one >> ");
for (int i = 0; i < list1.length; i++){
list1[i] = input.nextInt();
}
System.out.print("Enter list two >> ");
for (int i = 0; i < list2.length; i++){
list2[i] = input.nextInt();
}
// call the equality testing method and output whether or not the two lists are strictly identical or not.
if (equals(list1, list2) == true)
System.out.println("The two lists are strictly identical");
else
System.out.println("The two lists are not strictly identical");
}
// this method
public static boolean equals(int[] list1, int[] list2){
boolean bool = false;
if (Arrays.equals(list1, list2))
bool = true;
else
bool = false;
return bool;
}
}