将输入读取到每行具有不同列数的int 2D数组中



所以我们刚刚进行了一次小型的实践考试,要求我们阅读以下格式的输入,作为非语法问题的规则。实际的算法一点也不难做到,但我和我的同伴们一开始都不知道如何扫描这些输入。

4 4
1 1
1 2 3
1
1
0
2
1 1
2 2
*actual 4x4 grid here*

前两个整数表示行数(4)和列数。(4) 因此,接下来的四行表示每行的规则(第2行为1 2 3),接下来的4行表示每列的规则(列4为2 2),依此类推

在学习了一个学期的C之后,我们只处理了每行具有相同列数的数组,而在这个Java模块学习四周后,我们根本没有学会处理这种问题。

使用nextInt()和double-for循环扫描数组本来很容易,但如果没有零,我们都不太幸运。

1 1 0
1 2 3
1 0 0 
1 0 0

考试结束了,但我真的很生气,因为我不知道如何解决这个问题。非常感谢你们的真知灼见。

在Java中,您可以拥有不同长度的多维数组。

试试这个:

int rows = 4; // read
int cols = 4; // read
int[][] arr = new int[rows][]; // notice how we do not tell the cols here
for(int i=0,i<arr.length;i++){
// read line or somehow get the numbers of the line into an array
String line = ...
String[] splitLine = line.split(" ");
int[] rowArr = new int[splitLine.length];
for(int x=0;x<splitLine.length;x++){
// assume no NumberFormatException
rowArr[x] = Integer.parseInt(splitLine[x]);
}
arr[i] = rowArr;
}

然后你就有了4行的数组,但每行只有你需要的列:

{{1,1}、{1、2、3}、{1},{1}}

这是有效的,因为在Java中,多维数组只是对数组的引用数组。

最新更新