问题
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