2012-12-03 79 views
2

我的問題很簡單,我想在一個文本文件中讀取並將文件的第一行存儲到一個整數中,並將該文件的每隔一行存入一個多維數組中。我想這樣做的方法是創建一個if語句和另一個整數,當該整數爲0時,將該行存儲到整型變量中。雖然這看起來很愚蠢,並且必須有一個更簡單的方法。從文本文件中存儲輸入

例如,如果文本文件的內容是:

4 
1 2 3 4 
4 3 2 1 
2 4 1 3 
3 1 4 2 

第一行「4」,將被存儲在的整數,並且每一個其他線將進入多維數組。

public void processFile(String fileName){ 
    int temp = 0; 
    int firstLine; 
    int[][] array; 
    try{ 
     BufferedReader input = new BufferedReader(new FileReader(fileName)); 
     String inputLine = null; 

     while((inputLine = input.readLine()) != null){ 
      if(temp == 0){ 
       firstLine = Integer.parseInt(inputLine); 
      }else{ 
       // Rest goes into array; 
      } 
      temp++; 
     } 
    }catch (IOException e){ 
     System.out.print("Error: " + e); 
    } 
} 
+0

發佈您試圖做到這一點的一些代碼,我們可以批評它並提供改進。 –

+0

正如我所說,我有一個整數設置爲0,它被更新,並且一個if語句,當它是0時,將該行存儲在一個變量中。但似乎有一種方法可以爲我節省一些代碼。 – user123

+0

@MitchWheat:確保包含鏈接。 [你有什麼嘗試?](http://mattgemmell.com/2008/12/08/what-have-you-tried) – durron597

回答

2

我故意不回答這個問題。嘗試的東西:

  1. String.split
  2. 說像array[temp-1] = new int[firstLine];
  3. 的內部for環路與另一Integer.parseInt

這應該是足以讓你的方式,其餘的線

+0

我不在尋找代碼,只是一個不那麼愚蠢的做法。 – user123

+0

@ user1327636:你這樣做是完美的。你的代碼很好,只要把這兩個東西放在那一個地方// //休息進入數組中# – durron597

+0

@ user1327636:我將另一塊添加到元素#3 – durron597

0

相反,你可以將文件存儲爲一個整數的第一線,然後進入一個循環,你遍歷文件的行的其餘部分,將它們存儲在陣列中。這不需要if,因爲您知道第一個情況首先發生,而其他情況(數組)發生在之後。

0

我打算假設你知道如何使用文件IO。 我不是非常有經驗,但是這是我會怎麼去想:

while (inputFile.hasNext()) 
    { 
    //Read the number 
    String number = inputFile.nextLine(); 

    if(!number.equals(" ")){ 
     //Do what you need to do with the character here (Ex: Store into an array) 
    }else{ 
     //Continue on reading the document 
    } 
    } 

好運。

相關問題