我正在解决我正在研究的计算器程序的问题。我遇到的问题是我不知道如何让操作起作用。我已经尝试将它连接成一个String,然后以这种方式执行操作,但你不能这样做。我也尝试在操作数之间使用操作数和运算符(char b),但它不会执行操作。我现在唯一的解决方案是执行一系列检查以确定运算符是什么,然后使用该运算符执行等式,例如if (b == '-') { int answer = x-y;}
。我这样做的唯一问题是,它感觉很草率,并且可以以更有效的方式完成。
/**
* Makes sure that char b is a binary operator and returns the value made from x b y
*
* @param x first operand of integer value
* @param b the operation value
* @param y second operand of integer value
* @return the operation of x b y where b is the binary operator, +,-,/,*,%
*/
public int binaryOperation(int x, char b, int y)
{
if (!(b == '+' || b == '-' || b == '/' || b == '*' || b == '%'))
{
System.out.println("The character provided is not a valid binary operator. Please use one of the following characters:"
+ " '+', '-', '/', '*', or '%'.");
}
else
{
int answer =
return answer;
}
}
/**
* Makes sure that b is an unary operator and returns the value made from x b y
*
* @param x first operand of with an integer value
* @param b the operation value
* @param y second operand
* @return the operation of x b y where b is the unary operator, + or -
*/
public int unaryOperation(int x, char b, int y)
{
if (!(b == '+' || b == '-'))
{
System.out.println("The character provided is not a valid unary operator. Please use one of the following characters:"
+ " '+' or '-'.");
}
else
{
String function = System.out.println(x + b + y);
int answer = (int) function;
return answer;
}
}
答案 0 :(得分:9)
if (b == '+'){
return x+y;
}
else if (b == '-') {
return x-y;
}
等...
答案 1 :(得分:3)
更好的方法是使用switch语句,如下所示:
switch(b) {
case '+':
return x + y;
break;
case '-':
return x - y;
break;
case '*':
return x * y;
break;
...
}
等等。如果那是你的问题,那么java运算符就没有char转换器。希望它有所帮助!
您可以在此处详细了解switch语句及其语法:Switch Statement.
答案 2 :(得分:3)
您可以使用ScriptEngineManager,它可以执行eval
功能(JavaScript的评估)。
如:
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("js");
try {
Object result = engine.eval("(1 + 2)*3");
System.out.println(result);
} catch (ScriptException e1) {
e1.printStackTrace();
}
上面的代码输出9。