2016-03-02 107 views
-1

我必須從這樣的文件中讀取數據:從文件讀入2D陣列

4 
192 48 206 37 56 
123 35 321 21 41 
251 42 442 32 33 

的第一數目的候選的總數(列)和我需要存儲用於其它使用該值。然後我需要將剩餘的數據讀入二維數組中。我用我現在的版本更新了我的代碼,但它仍然無法工作。我不斷收到錯誤 java.util.NoSuchElementException:沒有找到行

public static int readData(int[][] table, Scanner in)throws IOException 
{ 
System.out.println("Please enter the file name: "); 
String location = in.next(); 
Scanner fin = new Scanner(new FileReader(location)); 
int candidates = fin.nextInt(); 
fin.nextLine(); 
for (int row = 0; row < 5; row++) { 
    for (int column = 0; column < candidates; column++) { 
    String line = fin.nextLine(); 
    fin.nextLine(); 
    String[] tokens = line.split(" "); 
    String token = tokens[column]; 
    table[row][column] = Integer.parseInt(token); 
    } 
} 
fin.close(); 
return candidates; 
} 

} 
+0

定義「完全不工作」。發生什麼事?華夫餅是否從屏幕上出來?首先,你忽略了「候選人」。其次,您只需閱讀第一行:'fin.nextLine();'應該在每次迭代中。 – Tunaki

+0

獲取錯誤 java.lang.NumberFormatException:對於輸入字符串:「」我輸入文件名後 – Zackary

+0

我如何忽略候選人?我不明白。 – Zackary

回答

0

據我瞭解,你的主要任務是從文件中提取整數值,並把它放入二維數組。

我建議你指在Oracle網站上的掃描儀API參考: https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html

你可以找到那裏,有你的任務多一些適當的方法:

  1. nextInt() - 用於從文件中直接獲取整數值
  2. hasNextLine() - 用於確定是否有下一行輸入

假設,即candidates列,它應該被視爲整數,不串:

int candidates = fin.nextInt(); 

隨着使用的掃描儀提到的方法,從文件中獲取String值將不再需要,因此linenumbers變量可能會從源代碼中完全刪除。

利用hasNextLine()的方法,你可以肯定,該文件將被讀取,直到其結束:

int row = 0; 
while(fin.hasNextLine()) {       //while file has more lines 
    for(int col = 0; col < candidates; j++) {  //for 'candidates' number of columns 
     table[row][col] = fin.nextInt();   //read next integer value and put into table 
    } 
    row++;           //increment row number 
} 

請記住,Java數組不是動態擴展

您的二維陣列 - table應該用準確的數據大小進行初始化。

在您當前的示例中,直到文件結束時才知道輸入行數,因此正確初始化數組可能需要額外的操作。

+0

幫了我一噸的兄弟現在完美的作品謝謝你的幫助 – Zackary

+0

很高興聽到:) 乾杯! – Fester