将2d数组读入三角形

use*_*790 1 java arrays

我想将以下内容读入2d锯齿状数组:

3
7 4
2 4 6
8 5 9 3
Run Code Online (Sandbox Code Playgroud)

我需要在每个输入上增加列大小.我不确定该怎么做.

我的代码如下:

int col = 1;
int[][] values = new int[rows][col];
for(int i = 0; i < values.length; i++){
  for(int j = 1; j < col; j++)
  {
     values[i][j] = kb.nextInt();
     col++;
  }
}
Run Code Online (Sandbox Code Playgroud)

Baz*_*Baz 5

这应该做到这一点.

int[][] values = new int[rows][];
for(int i = 0; i < values.length; i++)
{
    values[i] = new int[i+1];

    for(int j = 0; j < values[i].length; j++)
    {
        values[i][j] = kb.nextInt();
    }
}
Run Code Online (Sandbox Code Playgroud)

基本上,您首先要定义2d数组应该有多少行.

for循环中,为每行定义1d数组及其长度.

  • @davida.在添加下一个答案之前我会等几秒钟;) (2认同)