繁体   English   中英

Java 的 BufferedReader.readLine() 行为异常

[英]Java's BufferedReader.readLine() behaving unexpectedly

我有一个文件,其中包含一些赞美诗的乐谱。 它应该由 Java 程序读取,该程序会将这些赞美诗存储为对象。 每首赞美诗都是这样写的:

1
Hallelujah
C
Rythm

      C                  Am
I've |heard there was a |secret chord
$

'$' 只是 EOF 的标记。 我正在使用BufferedReader.readLine()逐行读取,直到“Rhytm”行初始化 Hymn object:

reader = new BufferedReader(new FileReader("/home/hal/teste.txt"));     
String linha = "", titulo, r, t; int n;
while(linha!="$") {
    n = Integer.parseInt(reader.readLine());     //reading the number
    titulo = reader.readLine();                  //reading the title
    Tom tom = new Tom(reader.readLine());        //reading the tone
    Ritmo ritmo = new Ritmo(reader.readLine());  //reading the rythm

    Hino hino = new Hino(n, titulo, tom, ritmo); //initializing the object

然后我只是分别阅读每一行。 问题是,第一个readLine()执行时,它读取的是第六行(“ C Am ”),而不是第一行(“ 1 ”)。 我尝试使用Scanner.nextInt()来获取该数字,但它给了我同样的错误。 那是我的控制台的 output:

Exception in thread "main" java.lang.NumberFormatException: For input string: "      C                  Am"
    at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.base/java.lang.Integer.parseInt(Integer.java:638)
    at java.base/java.lang.Integer.parseInt(Integer.java:770)
    at project/project.Build.main(Build.java:22)

Build.java:22是其中n = Integer.parseInt(reader.readLine()); 位于。 我究竟做错了什么?

只有文件的第一行包含 integer,因此不应在 while 循环中解析它。

在循环中,您应该只处理可重复的行。 正如@Fureeish 提到的,您还需要使用等号比较字符串。

通常解析行看起来像这样:

for (String linha = reader.readLine(); linha != null && !linha.equals("$"); linha = reader.readLine()) {
       ...
}

使用这个 for 循环,您可以逐行遍历文件。 在循环中,您应该处理不同的可能性。

最好的方法可能是在循环外处理前 4 行,然后在其中包含三个不同的情况:

  1. 这是一个空行
  2. 该行由注释组成
  3. 该行代表赞美诗文本

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM