2014-10-22 80 views
0

我正在讀取文件並將其複製到數組中。我的文件有五行文字,每句都有一個句子。我得到我的輸出「數組大小是5」,但之後沒有。如果我添加了陣列的打印線,它會給我5個空值...從文本文件讀入數組 - 獲取「空值」

有人可以幫助解釋我做錯了什麼嗎?謝謝!

public static int buildArray() throws Exception 
 
    { 
 
     System.out.println("BuildArray is starting "); 
 
    
 
     java.io.File textFile; // declares a variable of type File 
 
     textFile = new java.io.File ("textFile.txt"); //reserves the memory 
 
     
 
     Scanner input = null; 
 
      try 
 
      { 
 
       input = new Scanner(textFile); 
 
      } 
 
      catch (Exception ex) 
 
      { 
 
       System.out.println("Exception in method"); 
 
       System.exit(0); 
 
      } 
 

 
      int arraySize = 0; 
 
      while(input.hasNextLine()) 
 
       { 
 
        arraySize = arraySize + 1; 
 
        if (input.nextLine() == null) 
 
         break; 
 
       } 
 
     System.out.println("Array size is " + arraySize); 
 

 
     // Move the lines into the array 
 
     String[] linesInRAM = new String[arraySize];// reserve the memory 
 
     int count = 0; 
 
     if (input.hasNextLine()) 
 
      { 
 
       while(count < arraySize) 
 
       { 
 
        System.out.println("test"); 
 
        linesInRAM[count] = input.nextLine(); 
 
        System.out.println(linesInRAM[count]); 
 
        count = count + 1; 
 
       } 
 
      }

+3

你永遠不會重置掃描儀,所以它直到在文件的結尾... – MadProgrammer 2014-10-22 02:50:46

回答

0

在這段代碼

int count = 0; 
    if (input.hasNextLine()) 

以上hasNextLine將永遠是假的,你已經閱讀過該文件的所有道路。

將掃描儀重置爲文件的開頭,或使用動態列表,例如ArrayList添加元素。

0

我的Java有點生疏,但我的答案的基本要點是您應該創建一個新的Scanner對象,以便它再次從文件的開頭讀取。這是「重置」到最開始的最簡單方法。

你的代碼是目前沒有工作,因爲當你調用input.nextLine()你實際上是增加了掃描儀,因此在第一次while()input結束時坐在文件的末尾,所以當你再次調用它input.nextLine()返回null

Scanner newScanner = new Scanner(textFile); 

然後在你的代碼的底部,你的循環應該是這樣的,而不是:

if (newScanner.hasNextLine()) 
    { 
     while(count < arraySize) 
      { 
       System.out.println("test"); 
       linesInRAM[count] = newScanner.nextLine(); 
       System.out.println(linesInRAM[count]); 
       count = count + 1; 
      } 
    } 
+0

這是正是我需要的,謝謝你,謝謝。現在它正在工作。我不太清楚掃描儀是這樣工作的,謝謝你的解釋! – gerii 2014-10-22 05:24:26

+0

當然!確保點擊該複選標記和/或向上箭頭;) – yiwei 2014-10-22 14:53:04