如何编写用户输入的二维数组? [英] How to write user input 2D array?
本文介绍了如何编写用户输入的二维数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是Java新手.试图使其成为用户输入的2D数组,即4 * 4.但是当我尝试使用扫描仪时,行和列总是弄乱了.
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
感谢大家的帮助!
推荐答案
尝试以下方法:
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();
}
}
输出:
这篇关于如何编写用户输入的二维数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文