我尝试将按位运算符分配给变量。我该怎么做?
例如
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);
但是这不起作用。任何人请!!!
最佳答案
您可以制作自己的 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);
}
用法(添加一些异常处理):
String rFunction=JOptionPane.showInputDialog(null,"Enter Your round function","Round function",JOptionPane.INFORMATION_MESSAGE);
System.out.println(BitOperator.valueOf(rFunction.toUpperCase()).calc(x, y));
关于java - 在java中将按位运算符分配给变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37771046/