user1672790
user1672790

Reputation: 45

read 2d array into triangle

I want to read the following into a 2d jagged array:

3
7 4
2 4 6
8 5 9 3

I need to increase the column size on every input. I'm not exactly sure how to do it.

My code is as follows:

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++;
  }
}

Upvotes: 1

Views: 4168

Answers (2)

o_o
o_o

Reputation: 516

Sample

// don't fix the second dimension
int[][] values = new int[rows][];

for(i = 0; i < rows;i ++){
    //column size increases for every line input
    values[i] = new int[i+1];

    for(j = 0; j < values[i].length; j++) {
         values[i][j] = kb.nextInt();
    }
}

In Java, arrays do not have to be strictly rectangular. The variable values is a rows-element array of references to int arrays. Here, values[0] is a 1-element int array, values[1] is a 2-element int array, etc.

Upvotes: 1

Baz
Baz

Reputation: 36884

This should do it.

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();
    }
}

Basically, you start by defining how many rows your 2d array should have.

In the for loop, you define the 1d array for each row with its length.

Upvotes: 5

Related Questions