bad operand types for binary operator "&" java
Asked Answered
H

3

30

The error shows this line

 if ((a[0] & 1 == 0) && (a[1] & 1== 0) && (a[2] & 1== 0)){

This is the whole code:

public class Ex4 {

  public static void main(String[] args) {
  int [] a = new int [3];
  if(args.length == 3)
  {
      try{
        for(int i = 0; i < args.length; i++)
        {
        a[i] = Integer.parseInt(args[i]);
        }
        }
        catch(NumberFormatException e){
            System.out.println("Wrong Argument");
       }
      if ((a[0] & 1 == 0) && (a[1] & 1== 0) && (a[2] & 1== 0)){
        System.out.println("yes");
      }
    else {
        System.out.println("no");
    }
  }
  else{
      System.out.println("Error");
    }
}
}

I've fixed the code:

if ((a[0] & 1) == 0 && (a[1] & 1) == 0 && (a[2] & 1) == 0){

Was an issue with the brackets, updated for anyone in the future.

Horney answered 15/4, 2014 at 21:37 Comment(0)
C
66

== has higher precedence than &. You might want to wrap your operations in () to specify how you want your operands to bind to the operators.

((a[0] & 1) == 0)

Similarly for all parts of the if condition.

Contrecoup answered 15/4, 2014 at 21:39 Comment(0)
U
3

Because & has a lesser priority than ==.

Your code is equivalent to a[0] & (1 == 0), and unless a[0] is a boolean this won't compile...

You need to:

(a[0] & 1) == 0

etc etc.

(yes, Java does hava a boolean & operator -- a non shortcut logical and)

Underwing answered 15/4, 2014 at 21:39 Comment(1)
What does mean a non shortcut logical and?Premiere
A
0

You have to be more precise, using parentheses, otherwise Java will not use the order of operands that you want it to use.

if ((a[0] & 1 == 0) && (a[1] & 1== 0) && (a[2] & 1== 0)){

Becomes

if (((a[0] & 1) == 0) && ((a[1] & 1) == 0) && ((a[2] & 1) == 0)){
Angelineangelique answered 15/4, 2014 at 21:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.