0

I may just be tired and not thinking properly anymore, but why is "13" only printed once here? (intelliJ tells me that "i == 11 | i == 13" is always true but I don't see how that makes sense)

        for (int i = 0; i < 14; i++) {
            System.out.println(i);
            String line = clientReader.readLine();
            int length = line.length();
            if (i == 0 || i == 5 || i == 6) {
                line = line.substring(7, length - 6);
            } else if (i == 1 || i == 2 || i == 3 || i == 4 || i == 8 || i == 9 || i == 10 || i == 12) {
                line = line.substring(8, length - 7);
            } else if (i == 7) {
                line = line.substring(9, length - 8);
            } else if (i == 11 || i == 13) {
                line = line.substring(10, length - 9);

            }
            data[i] = line;
            System.out.println(i);
        }

p.s. The line.substring does not give an error, if I add System.out.println(line) at the end of the last else if it prints the correct thing.

2
  • 1
    use || instead of | in if conditions Commented Jan 27, 2018 at 21:16
  • Oh yeah will do, thanks. Commented Jan 27, 2018 at 21:19

1 Answer 1

2

The last else if is always true because your loop control variable runs from 0 until 13 and the only two numbers you haven't checked before the last else if is 11 and 13 therefore if none of the above conditions are true then i will either be 11 or 13 hence why IntelliJ is smart enough to know it's always true and hence control will always be bound inside the last else if block when the above conditions are not met.

If you increase the loop condition to something like i < 15 or above then IntelliJ wouldn't state else if (i == 11 || i == 13) is always true as i could be 14.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the explanation. That's not a problem though, right? This doesn't result in "13" only being printed once, does it?
my answer so far explains the part of your post --> "intelliJ tells me that "i == 11 | i == 13" is always true but I don't see how that makes sense" and not the --> "but why is "13" only printed once here?". that aside, how many times do you expect it to print 13 and why?
I was just making sure I wasn't missing anything in your explanation. Thanks for the explanation, it was helpful :). As to the printing issue, I made a dumb mistake; the array data was [13] instead of [14]. I was printing i to debug. I'll delete this post soon, its useles.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.