public static double[][] get2DArrayInput(int array1DLength) {
Scanner stdin = new Scanner(System.in);
System.out.println("Please enter the data for the two-dimensional array.");
int rows;
System.out.print("Please enter the number of columns of the 2D array: ");
int columns = stdin.nextInt();
double[][] twoDArray = new double[columns][];
do {
System.out.println("Please enter the array elements by rows: ");
for (int i = 0; i < columns; i++) {
for (int j = 0; j < twoDArray[i].length; j++) {
twoDArray[i][j] = stdin.nextDouble();
}
}
rows = twoDArray[0].length;
if (array1DLength != rows) {
System.out.println("Sorry, please ensure that the number of rows of the 2D array" +
" matches the length of the 1D array.");
}
} while (array1DLength != rows);
return twoDArray;
}
我试图在不知道行数的情况下逐行输入2D数组的行。我正在搞乱for循环,但我不确定它是什么。使用单个for循环而不是嵌套for循环会更好吗?
答案 0 :(得分:0)
您必须在此方案中初始化行和列的数量。数组是固定数量的大小,不能动态更改
在java上使用ArrayList ....您可以继续添加或删除...可以动态更改大小
例如: -
List<String> stringList = new ArrayList<String>();
stringList.add("String"); // adds a string value in this case
所以你的回答是
ArrayList<ArrayList<Double>> group = new ArrayList<ArrayList<Double>>(); // array list of array list
答案 1 :(得分:0)
您还没有在原始数组的每个索引处创建数组。
而不是:
for (int i = 0; i < columns; i++) {
for (int j = 0; j < twoDArray[i].length; j++) {
twoDArray[i][j] = stdin.nextDouble();
}
}
试试这个:
for (int i = 0; i < columns; i++) {
System.out.print("Please enter the number of rows: ");
int numrows = stdin.nextDouble();
twoDArray[i] = new double[numrows]; // need to initialize the array first
System.out.println("Please enter the array elements by rows: ");
for (int j = 0; j < twoDArray[i].length; j++) {
twoDArray[i][j] = stdin.nextDouble();
}
}
我建议您不知道数据结构的最终大小的解决方案使用可以动态更改的解决方案,例如ArrayList