Search code examples
javabuffered

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


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?


Solution

  • 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);