07arhoag
07arhoag

Reputation: 1

Storing Values to a 2 dimensional array in Java

Brand new to Java.

I'm trying to store values from a String to a 2D array in java. The first two values of my String give me rows and columns for a grid. From here, I need to use Integer.parseInt() to parse the values and assign them. I'm attempting do this using a for() loop, but I'm completely stuck. Here's what I have so far (notes included to indicate what I'm attempting to acheive):

    int r = Integer.parseInt(tokens[0]);
    rows = r;

    int c = Integer.parseInt(tokens[1]);
    cols = c;

    // create 2D array of int values
    // place the reference to the array object in grid variable

    int[][] input = new int[rows][cols];
    grid = input;

    //parse then store remaining values as int values in the 2D array using a nested loop

    for(int i = 0 ; i < tokens.length ; i++) {

        // read the next value and assign to next token
    }

Upvotes: 0

Views: 2380

Answers (1)

mvmn
mvmn

Reputation: 4057

Your code seems to be a bit off - you parse those numbers into int variables r and c but then do int[][] input = new int[rows][cols];. You don't have such variables as rows and cols.

Also you should not start with 0 in your loop since values tokens[0] and tokens[1] are for row and column counts.

Start loop at 2, or end it with tokens.length-2 and add 2 every time you take value from tokens inside the loop.

In order to calculate the row and column index you need to take your i (e.g. index in tokens array), adjust for the aforementioned offset of 2, floor-divide by column count to receive row number, and get a remainder of division by column count to get row number.

E.g.

for(int i = 2 ; i < tokens.length; i++) {
   int value = Integer.parseInt(tokens[i]);
   int idx = i-2;
   int row = Math.floorDiv(idx, c);
   int col = idx % c;
   grid[row][col] = value;
}

Upvotes: 1

Related Questions