My if statement ALWAYS returns true, no matter what

后端 未结 5 1444
轮回少年
轮回少年 2020-12-12 01:50

This just is\'t making sense to me at all.

This is my code:

boolean that = false;
        if (that == true);
        {
            System.out.println         


        
相关标签:
5条回答
  • 2020-12-12 02:12

    A common mistake. Remove the ; at the end of the if statement.

    BTW I always write the following if I use brackets and I use the code formatter of the IDE.

        if (that == true) {
            System.out.println("That is " + that);
        }
    

    This means if you have a mis-placed ; or { it can be more obvious.

    0 讨论(0)
  • 2020-12-12 02:14

    Try it like this:

        boolean that = false;
        if (that)
        {
            System.out.println("That is " + that);
        }
    

    Notice the extra semi-colon after the if in your code? That's why.

    The logical test is closed by the semi-colon, then the next block is always executed.

    If you remove the semi-colon it'll match your intuition.

    0 讨论(0)
  • 2020-12-12 02:23

    Remove the ;

    boolean that = false;
         if (that == true)
         {
             System.out.println("That is " + that);
         }
    

    otherwise the print is always executed.

    0 讨论(0)
  • 2020-12-12 02:26

    It's because of the semicolon you have here:

     if (that == true);
    

    Remove that semicolon ! It causes the code to do nothing after checking the conditional (that == true) - technically it's an "empty statement" - i.e. we can have a loop like so:

        for (int i = 0; ; i++){
          System.out.println("Thanks" );
        }
    

    And it would go forever!

    0 讨论(0)
  • 2020-12-12 02:26
    if (that == true);
                  // ^ The extra colon you dont need
    
    0 讨论(0)
提交回复
热议问题