2013-04-09 76 views
0

我正在寫一個「Move To Front」編碼器,它讀取給定的文件,然後將文件解析爲列表。它對編碼工作正常,但它只適用於只有一行的文件,我認爲問題出在while循環中。用java讀取文本文件

下面是代碼:

while ((line = br.readLine()) != 
     null) // While the line file is not empty after reading a line from teh text file split the line into strings 
{ 
    splitArray = line.split(" "); 
} 

for (int i = 0; i <= splitArray.length - 1; 
    i++) // for every string in the array test if it exists already then output data accordinly 
{ 
    if (FirstPass.contains(splitArray[i])) { 
    System.out.println(FirstPass.lastIndexOf(splitArray[i])); 
    FirstPass.addFirst(splitArray[i]); 
    FirstPass.removeLastOccurrence(splitArray[i]); 
    } else if (!FirstPass.contains(splitArray[i])) { 
    FirstPass.addFirst(splitArray[i]); 
    System.out.println("0 " + splitArray[i]); 
    } 
} 

System.out.println(" "); 
for (String S : FirstPass) { 
    System.out.println(S); 
} 
+0

對不起BR是一個緩衝的讀者 – 2013-04-09 23:15:43

+0

請編輯您的帖子和修復縮進。用適當數量的空格替換選項卡。 – 2013-04-09 23:17:01

+3

您的第一個while循環讀取整個文件並丟棄除最後一行之外的所有數據。 – 2013-04-09 23:17:53

回答

0

你的代碼解析splitArray是while循環外..所以只有最後一行將得到處理。

要處理的每一行,把while循環內整個for()塊..

while((line = br.readLine()) != null) // While the line file is not empty after reading a line from teh text file split the line into strings 
{ 
    splitArray = line.split(" "); 


    for(int i = 0; i <= splitArray.length - 1; i++)  // for every string in the array test if it exists already then output data accordinly 
    { 
     //.......... 
    } // end for 
} // end while 
+0

非常感謝你Kal我知道這將是一個小而愚蠢的東西。感謝您花時間回答我的問題 – 2013-04-09 23:23:27

0

支撐體系在錯誤的位置:

while((line = br.readLine()) != null) 
{ 
    splitArray = line.split(" "); 
} // This } shouuldn't be here... 
+0

刪除大括號會導致代碼編譯時錯誤。 – MathSquared 2013-04-09 23:24:04

+0

@ MathSquared11235 100%正確。我指出了問題的一般方面,並沒有給出完整的代碼來說明這個本地化的東西。 – John3136 2013-04-09 23:36:49