0

I try to assign bit wise operators into variables. How can i do it?

Eg

    String bitOp="";

        String rFunction=JOptionPane.showInputDialog(null,"Enter Your round function","Round function",JOptionPane.INFORMATION_MESSAGE);

         if(rFunction.toUpperCase()=="AND")
             bitOp="&";
         if(rFunction.toUpperCase()=="OR")
             bitOp="|";
         if(rFunction.toUpperCase()=="XOR")
             bitOp="^";

    int res= x +bitOp+ y; // if the operator is "AND" , this should be x & y.
                          //Here NumberFormatException error shows.
    System.out.print(res);

But it doesn't work. Anyone please!!!

2 Answers2

1

You could make your own BitOperator:

public enum BitOperator {
    AND {
        @Override
        public int calc(int x, int y) {
            return x & y;
        }
    },
    OR {
        @Override
        public int calc(int x, int y) {
            return x | y;
        }
    },
    XOR {
        @Override
        public int calc(int x, int y) {
            return x ^ y;
        }
    };

    public abstract int calc(int x,int y);

}

Usage(add some Exception handling):

          String rFunction=JOptionPane.showInputDialog(null,"Enter Your round function","Round function",JOptionPane.INFORMATION_MESSAGE);
          System.out.println(BitOperator.valueOf(rFunction.toUpperCase()).calc(x, y));
Turo
  • 4,724
  • 2
  • 14
  • 27
0

Your code shouldn't even compile so I am not sure of what you really want to achieve. Do you want to evaluate the String expression you create or do you just want to get the result more classically? Where do x and y come from...? There is an important part of your code that is missing.

Anyway I would chose the second option:

int eval;

String rFunction=JOptionPane.showInputDialog(null,"Enter Your round function","Round function",JOptionPane.INFORMATION_MESSAGE).toUpperCase();

 if(rFunction.equals("AND")){
     eval = x & y;
 } else if(rFunction.equals("OR")){
     eval = x | y;
 } else if(rFunction.equals("XOR")){
     eval = x ^ y;
 } else {
     //here you could also throw an exception
     //or loop and request the user to renew their choice
     System.out.print("Invalid choice");
     return;
 }

System.out.print(res);
C.Champagne
  • 5,381
  • 2
  • 23
  • 35