Java buffered reader stops reading lines, if i add a if statement in the while loop:

1.4k views Asked by At

I am creating a game engine from scratch with java, i have started work on a new save file instead of using imaages for maps:

Works and prints out every line:

while ((readString = buf.readLine()) != null) {
    System.out.println("Failed to assign action to line: " + readString);
}

Doesnt work, prints out first 3 lines:

while ((readString = buf.readLine()) != null) {
                if (readString.contains("Width:")){
                    readString.replace("Width:", "");
                    readString.trim();
                    Integer.parseInt(readString);
                    System.out.println(readString);
                }else if (readString.contains("Height:")){
                    readString.replace("Height::", "");
                    readString.trim();
                    Integer.parseInt(readString);
                    System.out.println(readString);
                }else{
                    System.out.println("Failed to assign action to line: " + readString);
                }
}

As you can see, the top one is working and prints out every line to the console, the second one stops after reading the 3rd line. I haven't found anything while researching the problem, and my syntax appears to be correct. What's wrong with my code?

2

There are 2 answers

0
Roger Lindsjö On BEST ANSWER

There is probably an exception that you are swallowing (catching and ignoring) un your program and this is the most probable candidates:

Strings are immutable so when you replace / trim the original string is the same, and a new one is returned.

} else if (readString.contains("Height:")){
    readString.replace("Height::", "");
    readString.trim();
    Integer.parseInt(readString);

Here you ignore the returned (new) strings and keep operating on the original string. Also, as you can see you check for Height: and the you remove Height:: (notice the double colon). So, unless your data actually contains Height:: the Height: will be left in the string when calling Integer.parseInt this causing an exception.

It should be more like this

} else if (readString.contains("Height:")){
    readString = readString.replace("Height:", "");
    readString = readString.trim();
    Integer.parseInt(readString);
3
JayL On

There probably is an exception that you are not seeing.

Put this around your code:

try {
   //.. your while-loop here
}
catch(Exception e) {
   e.printStackTrace();
}

Then fix the error.

Another hint: readString.replace("Width:", ""), readString.trim() and Integer.parseInt(readString) won't work. The functions don't change the variable itself, you need to assign their results to a variable.

Example:

 readString = readString.trim();