我有一个2D数组,其中需要用户输入以创建第一个尺寸长度,然后遍历并获取第二个尺寸长度。例如:如果用户为第一个维度输入4,则它将循环遍历4次并获得第二个维度长度,该长度可能为2、3、2、4。我不确定如何才能有效地完成此操作...
答案 0 :(得分:0)
您实际上不需要迭代内部数组,只需要做的就是迭代外部数组并获取每个内部数组的length属性。您可以通过简单的for
循环来完成此操作:
int[] arrayLengths = new int[outerArray.length];
for (int i = 0; i < outerArray.length; i++) {
arrayLengths[i] = outerArray[i].length;
}
或者,如果您愿意,可以使用streams:
int[] arrayLengths = Arrays.stream(outerArray)
.mapToInt(innerArray -> innerArray.length)
.toArray();
答案 1 :(得分:0)
使用此代码
import java.util.Arrays;
import java.util.Scanner;
public class MyClass {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter number of Arrays that 2D Array( Arrays of Arrays) should contain:");
int len = sc.nextInt();
int [][]arr2D = new int[len][];
for(int i=0; i<len; i++){
System.out.println("Enter length for Array at index "+i);
int innerlen = sc.nextInt();
arr2D[i] = new int[innerlen];
}
System.out.println(Arrays.deepToString(arr2D));
}
}
输出
Enter number of Arrays that 2D Array( Arrays of Arrays) should contain:
5
Enter length for Array at index 0
3
Enter length for Array at index 1
4
Enter length for Array at index 2
5
Enter length for Array at index 3
2
Enter length for Array at index 4
1
[[0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0], [0]]
index 01234
0|--- <- second dimension length tells how many element array at this index contains
1|----
2|-----
3|--
4|-
^
| first dimension length tells how many arrays are allowed in array of array