[英]How to write user input 2D array?
I am new to java. 我是Java新手。 Trying to make this into a user input 2D array which is 4*4. 试图使其成为用户输入的2D数组,即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! 感谢大家的帮助!
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();
}
}
Use following method to convert array String in 2D array. 使用以下方法将数组String转换为2D数组。
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.