Search code examples
javawhile-loopbufferedreader

Two conditions in While with Buffered reader


This is my first post. I am a beginner to Java.

I am trying to read a text file using BufferedReader. What I want to do is, it should only read lines starting with 'U' (I have lines starting with '#' which I want to ignore).

    String line = "";

    // reader is BufferedReader
    while (((line = reader.readLine()) != null) && (line.charAt(0) == 'U')) { // make sure only lines starting with 'U' are read
        Variant variant = new Variant(line);
        variants.add(variant); // list of Variant objects
    }

When I execute this, I get an empty list as output.

But when I try this,

    String line = "";

    // reader is BufferedReader
    while (((line = reader.readLine()) != null) ) { // make sure only lines starting with 'U' are read
        System.out.println("Char at 0: " + line.charAt(0));
        Variant variant = new Variant(line);
        variants.add(variant); // list of Variant objects
    }

Sure enough, it prints 'U' on the screen but I also get lines which don't start with 'U' as output.

Why is this happening? Is it because I am trying to assign some value to 'line' and checking it against some condition in the same expression ?


Solution

  • Don't try and put all of the logic in your while condition. Also, you could use String.startsWith(String) (or charAt(0) if you really prefer); but something like,

    String line;
    // reader is BufferedReader
    while (((line = reader.readLine()) != null)) {
        if (line.startsWith("#")) {
            continue;
        } else if (line.startsWith("U")) {
            Variant variant = new Variant(line);
            variants.add(variant); // list of Variant objects
        }
    }
    

    or

    String line;
    // reader is BufferedReader
    while (((line = reader.readLine()) != null)) {
        if (line.startsWith("U")) {
            Variant variant = new Variant(line);
            variants.add(variant); // list of Variant objects
        }
    }