Why does my boolean test in java always fail?

后端 未结 6 1396
别跟我提以往
别跟我提以往 2021-01-21 21:59

I am trying to make a boolean test so that if one of the tire pressures is below 35 or over 45 the system outputs \"bad inflation\".

In my class I must use a boolean, wh

相关标签:
6条回答
  • 2021-01-21 22:26

    It looks like you're never setting goodPressure to true. Maybe you want to start with it set to true, as it looks like your conditions will set it to false if necessary.

    Also, I think this line should throw a compiler warning (or error?)

    if (goodPressure = true)
    

    when compiling in Java. I thought the compiler wouldn't let you do an assignment in an if check, but maybe it does... I think you want it to be:

    if (goodPressure == true)
    

    Or just:

    if (goodPressure)
    
    0 讨论(0)
  • 2021-01-21 22:27

    Look at the last if statement. You are doing assignment not comparison.

    BTW. Your program will always return false once you do that... look at your logic. Where do you set goodPressure to true?

    0 讨论(0)
  • 2021-01-21 22:29

    Usually, code like if (variable = constantValue) is treated as compilation error in Java. However, there is an exception when the constant value is a boolean. In that case, the statement is equal to if (constantValue). This kind of issue can not be found in the compilation phase.

    So, I suggest 1)do not compare with boolean constant value, just do it by if (booleanVar); 2)always put the constant value ahead, like 'if (true = variable)' will cause the compilation fail.

    0 讨论(0)
  • 2021-01-21 22:38

    Your problem is that there is only a single = sign in the expression if (goodPressure = true). That assigns true to goodPressure and then checks to see if goodPressure is still true.

    You need to use a == or a .equals()

    0 讨论(0)
  • 2021-01-21 22:46
        if (goodPressure = true)
    

    Change this to:

        if (goodPressure == true)
    

    Or even better yet:

        if (goodPressure)
    

    Boolean comparison operators are == and !=. The = is an assignment operator.

    Also, you need to initially set goodPressure = true; before you check for violating conditions.

    0 讨论(0)
  • 2021-01-21 22:50

    you are initializing goodPressure to false, but then never assigning true, so it will always be false. Try initializing it to true.

    0 讨论(0)
提交回复
热议问题