How to write user input 2D array?

拥有回忆 提交于 2021-01-29 08:01:43

问题


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!


回答1:


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 :




回答2:


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


来源:https://stackoverflow.com/questions/43132454/how-to-write-user-input-2d-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!