如何使3D数组的第二个数组变得不同

huangapple 未分类评论76阅读模式
英文:

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 &lt; n; i++) {
            String[] line = reader.readLine().split(&quot; &quot;);
            int m = Integer.parseInt(line[0]);
            int k = Integer.parseInt(line[1]);
            array = new int[n][m][2];
            for (int j = 0; j &lt; m; j++) {
                String[] line2 = reader.readLine().split(&quot; &quot;);
                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];

huangapple
  • 本文由 发表于 2020年8月14日 23:05:36
  • 转载请务必保留本文链接:https://java.coder-hub.com/63415321.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定