[英]How to write user input 2D array?
我是Java新手。 試圖使其成為用戶輸入的2D數組,即4 * 4。 但是,當我嘗試使用掃描儀時,行和列總是弄亂了。
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);
}
我還希望用戶輸入可以輸出為:
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();
}
}
使用以下方法將數組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.