我有问题,想出一个解决方案,我的计算器程序,我正在工作。我遇到的问题是,我不知道怎样才能让手术开始工作。我尝试将它连接到一个字符串中,然后以这种方式执行操作,但您不能这样做。我也尝试让操作数和操作符(char )在操作数之间,但它不会执行操作。我现在唯一的解决方案是进行一系列检查,确定操作符是什么,然后使用该运算符(如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;
}
}
发布于 2016-02-26 02:15:44
if (b == '+'){
return x+y;
}
else if (b == '-') {
return x-y;
}
等等。
发布于 2016-02-26 02:21:49
更好的方法是使用switch语句,如下所示:
switch(b) {
case '+':
return x + y;
break;
case '-':
return x - y;
break;
case '*':
return x * y;
break;
...
}
诸若此类。如果这是您的问题,则没有char转换器到java操作符。希望能帮上忙!
您可以在这里阅读有关开关语句及其语法的更多信息:开关语句。
发布于 2016-02-26 02:31:55
您可以使用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。
https://stackoverflow.com/questions/35642117
复制相似问题