can you have two conditions in an if statement

后端 未结 6 1528
鱼传尺愫
鱼传尺愫 2020-12-22 13:48

I\'m a beginner in coding. I was recently working with to create a chatting programme where a user will chat with my computer. Here is a part of the code:

Sy         


        
6条回答
  •  不知归路
    2020-12-22 14:05

    This is probably more answer than you need at this point. But, as several others already point out, you need the OR operator "||". There are a couple of points that nobody else has mentioned:

    1) If (b.equals("good") || b.equals("it was good")) <-- If "b" is null here, you'll get a null pointer exception (NPE). If you are genuinely looking at hard-coded values, like you are here, then you can reverse the comparison. E.g.

    if ("good".equals(b) || "it was good".equals(b))

    The advantage of doing it this way is that the logic is precisely the same, but you'll never get an NPE, and the logic will work just how you expect.

    2) Java uses "short-circuit" testing. Which in lay-terms means that Java stops testing conditions once it's sure of the result, even if all the conditions have not yet been tested. E.g.:

    if((b != null) && (b.equals("good") || b.equals("it was good")))

    You will not get an NPE in the code above because of short-circuit nature. If "b" is null, Java can be assured that no matter what the results of the next conditions, the answer will always be false. So it doesn't bother performing those tests.

    Again, that's probably more information than you're prepared to deal with at this stage, but at some point in the near future the NPE of your test will bite you. :)

提交回复
热议问题