2015-08-18 110 views
0

我從一個文本文件,它看起來像這樣寫着:當我從文本文件中讀取時,如何跳過行?

1 
The Adventures of Tom Sawyer 
2 
Huckleberry Finn  
4  
The Sword in the Stone  
6 
Stuart Little 

我必須讓這個用戶可以輸入參考號和程序將執行二進制和線性搜索和輸出稱號。我的老師說要使用兩個ArrayLists,一個用於數字,另一個用於標題,並輸出它們。我只是不知道如何跳過線條,所以我可以添加到相應的數組列表。

int number = Integer.parseInt(txtInputNumber.getText()); 
    ArrayList <String> books = new ArrayList <>(); 
    ArrayList <Integer> numbers = new ArrayList <>(); 
    BufferedReader br = null; 

    try { 
     br = new BufferedReader(new FileReader("bookList.txt")); 
     String word; 
     while ((word = br.readLine()) != null){ 
      books.add(word); 
     } 


    } catch (IOException e) { 
     e.printStackTrace(); 
    } finally { 
     try { 
      br.close(); 
     } catch (IOException ex) { 
      ex.printStackTrace(); 
     } 
    } 

在此先感謝,我感謝任何幫助!

+0

我認爲你需要跳過空行,並處理(處理爲相反的跳過)其他行。我認爲,你必須做一些解析過程。例如,詢問該行的第一個單詞是否是數字,可以假定是數字行,否則將行作爲書籍標題處理。 – Victor

+0

爲什麼不在while循環中添加一些代碼。您也許可以將布爾變量從true變爲false,然後根據布爾值編寫適當的列表。很多事情你可以嘗試。 –

+0

第3章和第5章在哪裏? –

回答

0

您可以檢查,如果你在偶數或奇數行由行號做模2操作:

try (BufferedReader br = new BufferedReader(new FileReader("bookList.txt"))) { 
    String word; 
    int lineCount = 0; 
    while ((word = br.readLine()) != null){ 
     if (++lineCount % 2 == 0) { 
      numbers.add(Integer.parseInt(word)); 
     } else { 
      books.add(word); 
     } 
    } 
} catch (IOException e) { 
    e.printStackTrace(); 
} 
+0

工作,這很有效,謝謝! –

0
int number = Integer.parseInt(txtInputNumber.getText()); 
ArrayList <String> books = new ArrayList <>(); 
ArrayList <Integer> numbers = new ArrayList <>(); 
BufferedReader br = null; 

try { 
    br = new BufferedReader(new FileReader("bookList.txt")); 
    String word; 
    while ((word = br.readLine()) != null){ 
      numbers.add(Integer.valueOf(word)); 
      word = br.readLine() 
      books.add(word); 
    } 


} catch (IOException e) { 
    e.printStackTrace(); 
} finally { 
    try { 
     br.close(); 
    } catch (IOException ex) { 
     ex.printStackTrace(); 
    } 
} 
0

你可以做檢查,看看它實際上是一個整數,你從文件中讀取。至於我記得,有沒有內置的方法來做到這一點,但你可以自己定義爲:

boolean tryParseInt(String value) { 
    try { 
     Integer.parseInt(value); 
     return true; 
    } catch (NumberFormatException e) { 
     return false; 
    } 
} 

然後,只需做一個檢查,看看如果您在閱讀該行是一個整數或不。

int number = Integer.parseInt(txtInputNumber.getText()); 
ArrayList <String> books = new ArrayList <>(); 
ArrayList <Integer> numbers = new ArrayList <>(); 
BufferedReader br = null; 

try { 
    br = new BufferedReader(new FileReader("bookList.txt")); 
    String word; 

    while ((word = br.readLine()) != null){ 
     if (tryParseInt(word)) 
      numbers.add(Integer.parseInt(word)) 
     else 
      books.add(word); 
    } 
} catch (IOException e) { 
    e.printStackTrace(); 
} finally { 
    try { 
     br.close(); 
    } catch (IOException ex) { 
     ex.printStackTrace(); 
    } 
} 

希望得到這個幫助!

相關問題