英文:
How to make 3d array's second array to be different
问题
public class StackSize {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(
new InputStreamReader(System.in));
int n = Integer.parseInt(reader.readLine());
int[][][] array = new int[n][][];
for (int i = 0; i < n; i++) {
String[] line = reader.readLine().split(" ");
int m = Integer.parseInt(line[0]);
int k = Integer.parseInt(line[1]);
array[i] = new int[m][2]; // Changed this line
for (int j = 0; j < m; j++) {
String[] line2 = reader.readLine().split(" ");
int cm = Integer.parseInt(line2[0]);
int pm = Integer.parseInt(line2[1]);
array[i][j][0] = cm;
array[i][j][1] = pm;
}
}
}
}
英文:
Can somebody help me?
I want to have an array like this. [[[10, 75]], [[10, 75],[20, 80]], [[10, 75], [15, 80], [20, 90]]]
And this is my code:
public class StackSize {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(
new InputStreamReader(System.in));
int n = Integer.parseInt(reader.readLine());
int[][][] array = new int[n][][];
for (int i = 0; i < n; i++) {
String[] line = reader.readLine().split(" ");
int m = Integer.parseInt(line[0]);
int k = Integer.parseInt(line[1]);
array = new int[n][m][2];
for (int j = 0; j < m; j++) {
String[] line2 = reader.readLine().split(" ");
int cm = Integer.parseInt(line2[0]);
int pm = Integer.parseInt(line2[1]);
array[i][j][0] = cm;
array[i][j][1] = pm;
}
}
}
}
My code is saving only the last inputs. Like, if I enter [[[10, 75]], [[10, 75],[20, 80]], [[10, 75], [15, 80], [20, 90]]] my array will look like [[[0, 0],[0, 0],[0, 0]], [[0, 0],[0, 0],[0, 0]], [[10, 75], [15, 80], [20, 90]]]. I want the second array to be different every time.
答案1
得分: 0
array = new int[n][m][2];
重新赋值`array`,创建一个新的三维数组,填充为零 - 因此,如果您之前已经向其中放入了值,它们将丢失。
相反,只需为`array[i]`分配一个新的二维数组:
array[i] = new int[m][2];
英文:
array = new int[n][m][2];
reassigns array
, creating a new 3d array filled with zeros - so if you've previously put values into it, they are lost.
Instead, just assign a new 2d array to array[i]
:
array[i] = new int[m][2];
专注分享java语言的经验与见解,让所有开发者获益!
评论