首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用字符运算符执行操作

使用字符运算符执行操作
EN

Stack Overflow用户
提问于 2016-02-26 02:08:23
回答 3查看 3.9K关注 0票数 3

我有问题,想出一个解决方案,我的计算器程序,我正在工作。我遇到的问题是,我不知道怎样才能让手术开始工作。我尝试将它连接到一个字符串中,然后以这种方式执行操作,但您不能这样做。我也尝试让操作数和操作符(char )在操作数之间,但它不会执行操作。我现在唯一的解决方案是进行一系列检查,确定操作符是什么,然后使用该运算符(如if (b == '-') { int answer = x-y;} )执行等式。这样做的唯一问题是,我觉得这样做很草率,而且可以用一种更有效的方式进行。

代码语言:javascript
运行
复制
/**
 * 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;
    }
}
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2016-02-26 02:15:44

代码语言:javascript
运行
复制
if (b == '+'){
   return x+y;
}
else if (b == '-') { 
   return x-y;
}

等等。

票数 13
EN

Stack Overflow用户

发布于 2016-02-26 02:21:49

更好的方法是使用switch语句,如下所示:

代码语言:javascript
运行
复制
switch(b) {
    case '+':
        return x + y;
        break;
    case '-':
        return x - y;
        break;
    case '*':
        return x * y;
        break;

    ...

}

诸若此类。如果这是您的问题,则没有char转换器到java操作符。希望能帮上忙!

您可以在这里阅读有关开关语句及其语法的更多信息:开关语句。

票数 3
EN

Stack Overflow用户

发布于 2016-02-26 02:31:55

您可以使用ScriptEngineManager,它可以执行eval函数(JavaScript的实用程序)。

例如:

代码语言: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。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35642117

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档