简体   繁体   中英

Java's BufferedReader.readLine() behaving unexpectedly

I have a file that contains scores for some hymns. It is supposed to be read by a Java program that will store these hymns as objects. Each hymn is written like this:

1
Hallelujah
C
Rythm

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

The '$' is just a token for EOF. I'm using BufferedReader.readLine() to read line by line until the 'Rhytm' line to initialize a 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

And then I just read each line separatedly. The problem is, the first readLine() executes, it reads the sixth line (" C Am "), not the first one(" 1 "). I've tried using Scanner.nextInt() to get that number, but it gives me the same error. That's my console's 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 is where n = Integer.parseInt(reader.readLine()); is located. What am I doing wrong?

Only the first line of your file contains an integer, so you should not parse it within the while loop.

Within the loop you should process only the lines that are repeatable. As @Fureeish mentioned you also need to compare string using equals.

Usually parsing lines looks something like this:

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

With this for loop you iterate through the file line by line. Within the loop you should have handling for the different possibilities.

The best way would probably be to handle the first 4 lines outside the loop and then have the three distinctive cases within:

  1. it is an empty line
  2. The line consists of notes
  3. The line represents the hymn text

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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