0

I am new to java. Trying to make this into a user input 2D array which is 4*4. But when I try scanner, the row and col always got messed up.

public static void main(String[] args) {
        String array = "1 2 2 1,1 3 3 1,1 3 3 2,2 2 2 2"; 
        int[][] input = parseInt(array, 4, 4);
}

And I also want the user input can output as:

1 2 2 1
1 3 3 1
1 3 3 2
2 2 2 2

Appreciate for everybody's help!

2

2 Answers 2

2

Try this one :

 public static void main(String args[]) {

    String array = "1 2 2 1,1 3 3 1,1 3 3 2,2 2 2 2";
    int[][] input = new int[4][4];//4*4 
    String[] inputs = array.split(",");
    for (int i = 0; i < inputs.length; i++) {
        String[] cols = inputs[i].split(" ");
        for (int j = 0; j < cols.length; j++) {
            input[i][j] = Integer.parseInt(cols[j]);
            System.out.print(input[i][j]);
            System.out.print(" ");// for spacing
        }

        System.out.println();

    }
}

Output : this is the output

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

Comments

-1

Use following method to convert array String in 2D array.

int[][] parseInt(String array, int row, int col) {
    int[][] arr = new int[row][col];

    String[] rowStr = array.split(",");

    for (int i = 0; i < rowStr.length; i++) {
        String[] colStr = rowStr[i].split(" ");
        for (int j = 0; j < colStr.length; j++) {
            arr[i][j] = Integer.parseInt(colStr[j]);
        }
    }
    return arr;
}

Comments

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.