[英]How to create a 2D array by scanning a file
我正在嘗試讀取文件並生成2D數組。 所以我相信我的構造函數會創建正確的尺寸,只是我不知道如何將實際值輸入到數組中。
文件格式:
6
1 4 2 2 2 3
4 2 2 4 1 2
2 1 3 4 3 2
1 3 3 2 6 2
0 0 0 2 0 0
3 4 0 0 0 0
0 0 0 1 0 0
0 1 0 0 0 0
0 0 0 0 0 6
5 0 1 0 0 4
文件輸入在左側,木板結果應類似於右側:
6 | 1 4 2 2 2 3
1 4 2 2 2 3 | -----------
4 2 2 4 1 2 | 1|. . . 2 . .|4
2 1 3 4 3 2 | 3|3 4 . . . .|2
1 3 3 2 6 2 | 3|. . . 1 . .|2
0 0 0 2 0 0 | 2|. 1 . . . .|4
3 4 0 0 0 0 | 6|. . . . . 6|1
0 0 0 1 0 0 | 2|5 . 1 . . 4|2
0 1 0 0 0 0 | -----------
0 0 0 0 0 6 | 2 1 3 4 3 2
5 0 1 0 0 4 |
文件的第一行是面板的大小(6x6)。
第二行是面向“北向南(NS)”的值
第三行是面向“ East to West(EW)”的值
第四行是面向“南到北(SN)”的值
第五行是面向“西向東(WE)”的值。
其余的行將填充到板上。 0
不會放入任何內容。
public static final int EMPTY = 0;
int[][] board;
int dim;
int[] NS, SN, EW, WE; //the outter arrays
public SkyscraperConfig(Scanner f){
while(f.hasNextLine()){
if(f.nextLine().length() == 1){
dim = f.nextInt();
}
else{
outterArrays = f.nextLine().length();
}
}
this.board = new int[dimension+1][dimension+1];//I made the dimension +1 to hold the outter arrays that hold the NS, SN, EW, and WE values
this.NS = new int[outterArrays+1];
this.SN = new int[outterArrays+1];
this.EW = new int[outterArrays+1];
this.WE = new int[outterArrays+1];
}
我的想法是創建一個2D數組,它是文件中第一行的大小。 然后,為外部值創建代表外部的四個數組。 我不知道如何將那些外部數組放入2D數組中。
與所有文件讀取一樣,嘗試將每個任務分隔為不同的任務。 問問自己“我需要做些什么,然后才能完成?” 希望任務按順序列出(每個任務只需要文件中位於其上方的信息),這種情況就是您遇到的問題。
您的任務似乎涉及三個子任務:
因此,讓我們一起工作:
int[][] board;
int dim;
int[] NS, SN, EW, WE; //the outter arrays
public SkyscraperConfig(Scanner f){
//First line should be dimension line
int dim = Integer.parseInt(f.nextLine());
//Initalize data structures based off of this dimension
this.NS = new int[dim];
this.SN = new int[dim];
this.EW = new int[dim];
this.WE = new int[dim];
this.board = new int[dim][dim];
//Read in side arrays
//...
//Read in the board
//...
}
在這里我們可以猜測,在閱讀這些行時,我們將有很多重復的代碼-可能是時候開始設計輔助方法了。 我們似乎要做的很多事情是一行讀取並解析其中的所有整數。 所以我們來寫一個方法
private static int[] parseIntLine(String line){
String[] arr = line.trim().split(' '); //Split on the space character
int[] intArr = new int[arr.length];
for(int i = 0; i < arr.length; i++){
intArr[i] = Integer.parseInt(arr[i]);
}
return intArr;
}
現在,我們可以使用此方法來完成我們的實現,讓讀取過程可以照顧到數組的長度:
public SkyscraperConfig(Scanner f){
//First line should be dimension line
int dim = Integer.parseInt(f.nextLine());
//Only actual initialization we have to do is for the matrix's outer array
board = new int[dim][];
//Read in side arrays
NS = parseIntLine(f.nextLine());
EW = parseIntLine(f.nextLine());
SN = parseIntLine(f.nextLine());
WE = parseIntLine(f.nextLine());
//Read in the board - dim rows to read
for(int i = 0; i < dim; i++){
board[i] = parseIntLine(f.nextLine());
}
f.close();
}
現在,很多事情可能會出錯,您應該考慮一下。 如果第一行包含多個數字怎么辦? 如果第一行包含非整數值怎么辦? 如果側面陣列之一或板行之一的長度錯誤怎么辦? 如果沒有足夠的行來填充董事會怎么辦? 如果行太多怎么辦? 對於每個問題,您都應該在方法中處理情況(通過try / catch或if-else邏輯),或者如果它是無法解決的問題,則拋出某種異常。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.