Or operand with int in if statement

前端 未结 12 1941
傲寒
傲寒 2021-01-25 07:45

My problem is that program is not reading codes as i intended \"he\" would.

I have

if (hero.getPos() == (6 | 11 | 16)) {
    move = new Object[] {\"Up\",         


        
相关标签:
12条回答
  • 2021-01-25 08:00

    No. You could create a Set<Integer> once and then use that, or just:

    int number = ci.getNumber();
    if (number == 6252001 || number == 5855797 || number == 6251999)
    

    I'd also consider changing those numbers into constants so that you get more meaningful code.

    0 讨论(0)
  • 2021-01-25 08:00

    Java won't let you do that. You can do a hash lookup (which is overkill for this) or a case statement, or a big honking ugly multiple compare:

    if ((n==1 ) || (n==2) || ...
    
    0 讨论(0)
  • 2021-01-25 08:02

    You cannot do it like that. It ors the 3 number bitwise.

    You have to do like this :

    if (hero.getPos() == 6 || hero.getPos() == 11 | hero.getPos() == 16)) {
        move = new Object[] {"Up", "Right", "Left"};
    } else {
        move = new Object[] {"Up", "Down", "Right", "Left"};
    }
    

    You see the difference ? | is a bitwise or while || is a logical or. Note also that you have to rewrite the comparison each time.

    0 讨论(0)
  • 2021-01-25 08:02

    (6 | 11 | 16) would be evaluated first to 31 (binary operation), which is 6 != 31. Not what you want.

    Better is to check every single position (you have only 3, so inline is good, for more consider using a loop):

    if (hero.getPos() == 6 || hero.getPos() == 11 | hero.getPos() == 16)) {
        move = new Object[] {"Up", "Right", "Left"};
    } else {
        move = new Object[] {"Up", "Down", "Right", "Left"};
    }
    
    0 讨论(0)
  • 2021-01-25 08:02

    no.. you have to compare them individually.

    0 讨论(0)
  • 2021-01-25 08:08

    No, you're going to need to check ci.getNumber() == ... for each value, or add them to a collection and check myCollection.contains(ci.getNumber()). However, you may want to re-think the structure of your code if you are checking a method against several known values.

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