2014-12-03 39 views
-1

我試圖讀取文件兩次,但它似乎只有第一個while while循環運行。基本上,我用第一個while循環來計數元素,我分配了數組的大小。我用第二個調用方法並傳遞字符串(每個元素)。我試圖通過使用while循環來執行這兩個任務,但我很難設置數組的大小。如何讀取文件兩次

請幫助,如果有人知道如何做到這一點。我期待聽到你們的聲音。

預先感謝您

public static void main(String[] args)throws Exception 
{ 
    Scanner scan = new Scanner(new FileReader("first.txt")); 
    int count = 0; 
    while(scan.hasNext()) 
    { 
     count ++; 
     String s = scan.next(); 
    } 

    ArrayList<String> []words = new ArrayList[count]; 
    while(scan.hasNext()) 
    { 
     String f = scan.next(); 
     hash(f,count); //call method 
    } 
    scan.close(); 
    //System.out.println(count); 


} 
+1

您是否嘗試過在兩次調用之間重置掃描?因爲當你正在做第二次迭代時,它的'.hasNext()'方法結束了。 – Emz 2014-12-03 02:11:38

+1

第一個循環結束,因爲'scan.hasNext()'返回false。在下一個循環之前,你並沒有對'scan'做任何事情,所以你認爲'hasNext()'會返回除false之外的任何東西(就像它上次一樣...) – John3136 2014-12-03 02:12:56

+0

我試圖使用reset();但似乎沒有任何工作。無論如何回到文件的第一行? – danny 2014-12-03 03:01:09

回答

0

你並不需要指定一個尺寸一個ArrayList的。它將根據需要處理大小調整。

public static void main(String[] args)throws Exception 
{ 
    Scanner scan = new Scanner(new FileReader("first.txt")); 
    ArrayList<String> words = new ArrayList<String>(); 
    while(scan.hasNext()) 
    { 
     String s = scan.next(); 
     words.add(s); 
    } 
    scan.close(); 
}