1

I'm trying to populate a 2d array in java for a sudoku board. The numbers come from a csv file. The issue is the code just reads the first four numbers, then restarts at 0 again for a new row. How do I stop this from happening, and get it to continue to the end of the numbers?

    String[] lines = Cell.toCSV().split(",");
    int[] intArray = new int[lines.length];

    for (int i = 0; i < intArray.length; i++) {
        intArray[i] = Integer.parseInt(lines[i]);
    } //convert string to int

    int[][] dataArray = new int[4][4]; //4x4 sudoku game

    for (int col = 0; col < size; col++) {
        for (int row = 0; row < dataArray[col].length; row++) {
            dataArray[col][row] = intArray[row];
    }

1 Answer 1

1

You need a separate counter for the original array :

int index = 0;
for (int col = 0; col < dataArray.length; col++) {
    for (int row = 0; row < dataArray[col].length; row++) {
        dataArray[col][row] = intArray[index++];
}

This is assuming the intArray has enough values to populate the 2D array. You should probably validate that prior to this loop.

BTW, the first dimension of a 2D array is usually considered as the row, not the column, so your loop variable names are a bit confusing.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, that was the solution :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.