当我从文本文件中读取时,如何跳过行?

问题描述:

我从一个文本文件,它看起来像这样写着:当我从文本文件中读取时,如何跳过行?

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章在哪里? –

您可以检查,如果你在偶数或奇数行由行号做模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

工作,这很有效,谢谢! –

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(); 
    } 
} 

你可以做检查,看看它实际上是一个整数,你从文件中读取。至于我记得,有没有内置的方法来做到这一点,但你可以自己定义为:

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(); 
    } 
} 

希望得到这个帮助!