gpt4 book ai didi

java - 在java中将按位运算符分配给变量

转载 作者:行者123 更新时间:2023-12-01 21:28:15 25 4
gpt4 key购买 nike

我尝试将按位运算符分配给变量。我该怎么做?

例如

    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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com