在Java中将字符串转换为运算符(+*/-)

6

我正在使用Stack类来计算涉及整数的简单算术表达式,例如1+2*3。您的程序将按照给定的顺序执行操作,而不考虑运算符的优先级。

因此,表达式1+2*3应该被计算为(1+2)*3=9,而不是1+(2*3)=7。

如果我的输入是1+2*3,我知道如何将字符串1、2、3转换为整数,但我不知道如何将+和*从字符串类型转换为运算符。

我的代码逻辑是:

例如:给定字符串2 + (3 * 5),所以首先会执行3 * 5,然后在3 * 5的结果上执行+2。


为什么不能这样写 if(currChar.equals("*")) - No Idea For Name
没有“operator”类型。根据字符串值调用正确的操作。 - Robby Cornelissen
好的。如果我得到输入 (a+b)*c,我可以做什么? - user4120685
你能否更具体地说明“简单”表达式的含义?你能给出一些例子吗?你的简单表达式是否已经有括号了?如果是,你能提供一些如何评估这些表达式的示例吗? - Chan
我的代码逻辑是:例如,给定字符串2 + 3 * 5,所以先执行3 * 5,然后在3 * 5的结果中执行+2。谢谢。您能否发布执行此操作不正确的代码,以便我们可以建议更正。 - Chan
显示剩余4条评论
6个回答

7

可能最好的方法是使用 equals,但最好忽略空格:

我不太确定您如何拆分字符串,但例如,如果您有一个字符 op 和两个整数 ab

String str = op.replace(" ", "");

if(str.equals("*")){
   retVal = a*b;
} else if(str.equals("+")){
   retVal = a+b;
}//etc

3
有没有可能让 * 有小写形式和大写形式? - committedandroider
@committedandroider 嗯... 可能不是,我想忽略空格并认为 ignoreCase 会这样做。现在已经更改了... - No Idea For Name
@No Idea For Name 我仍然无法弄清楚用户用于计算表达式值的当前逻辑是什么,当他/她说简单表达式时,'简单'是什么意思。我的意思是,原始问题还是如此不明确,因此我有点不理解所有这些提出的解决方案。只是这样说... - Chan
@Chan 我同意你的观点,因此向原帖作者要求了代码。我想要理解他做了什么以及他期望得到什么。 - No Idea For Name

3
快速解决方案:使用以下代码在Java中执行正确的JavaScript算术表达式。
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine se = manager.getEngineByName("JavaScript");        
    try {
        Object result = se.eval(val);
        System.out.println(result.toString());
    } catch (ScriptException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

3

按照Ogen的建议,手动检查运算符。快速完成if、else if....结构的方法是使用switch语句,即

switch(operand) {
case "*":
      break;
case "+":
      break; 
 .....
 default:
}

2
您需要手动检查并分配运营商。例如:
if (s.equals("+")) {
    // addition
}

0

好的,假设您的任务需要使用Stack类,并且您已经有了选择数字(包括负数--在除一个情况外的所有情况下都是一个运算符后跟另一个运算符)和运算符以及括号的逻辑,您可以按照以下步骤进行。

如果遇到数字,请从堆栈中弹出最后两个元素。您弹出的第一个项目将是运算符,下一个将是数字。计算表达式并将其推入Stack中并继续。

您可以忽略括号。您还必须处理第一次读取数字或括号的情况。


0
说实话,我也在寻找答案。我想制作一个计算器应用程序,所以我试图直接将字符串转换为操作,但在网上搜索了几个小时后,我什么也没找到,最终我自己编写了程序,但由于我是初学者,这并不容易。 所以这是我的程序,它不能使用括号或逗号。 您只能使用四个运算符“+ - * /”,但除此之外,一切似乎都正常。
程序相当简单,只需从除法开始,取两个数字和表示运算符的字符串,然后将其切成三个字符串,然后对两个数字执行操作,然后用结果替换操作,直到没有除法为止。 然后依次进行乘法,减法和加法。
以下是我的函数描述: orderOp:调用其他函数 getOp:获取操作的字符串,因此如果您给出了“2 + 4 * 5/6”,则会得到5/6 cutString:将字符串分成三个部分,因此如果您提供了5/6,则会得到包含["5","/","6"]的字符串数组 Op:获取cutString的数组,并根据arr [1](在本例中为“/”)执行数学计算
class Operateur{
private static final DecimalFormat decfor = new DecimalFormat("0.00");
public static String Op(String s){
    String[] equation = cutString(s);
    double sol = 0;
    switch (equation[1]){
        case "/":
            sol = Double.parseDouble(equation[0])/Double.parseDouble(equation[2]);
            break;
        case "*":
            sol = Double.parseDouble(equation[0])*Double.parseDouble(equation[2]);
            break;
        case "+":
            sol = Double.parseDouble(equation[0])+Double.parseDouble(equation[2]);
            break;
        case "-":
            sol = Double.parseDouble(equation[0])-Double.parseDouble(equation[2]);
            break;
    }
    return sol+"";
}


public static String[] cutString(String s){
    String[] arr = new String[0];
    if(s.contains("+")){
        arr = s.split("((?=[//+])|(?<=[//+]))");
    }
    if(s.contains("-")){
        arr = s.split("((?=-)|(?<=-))");
    }
    if(s.contains("*")){
        arr = s.split("((?=[//*])|(?<=[//*]))");
    }
    if(s.contains("/")){
        arr = s.split("((?=[///])|(?<=[///]))");
    }
    return arr;
}


public static void orderOp(String equation){
    while(equation.contains("/")){
        equation = equation.replace(getOp(equation),(decfor.format(Double.parseDouble(Op(getOp(equation))))).replace(',', '.'));

    }
    System.out.println("Division :" +equation);
    while(equation.contains("*")){
        equation = equation.replace(getOp(equation),decfor.format(Double.parseDouble(Op(getOp(equation)))).replace(',', '.'));
    }
    System.out.println("Multiplication:" +equation);
    while(equation.contains("+")){
        equation = equation.replace(getOp(equation),Op(getOp(equation)));
    }
    System.out.println("addition:" +equation);
    while(equation.contains("-")&& (equation.replaceAll("[^.]", "").length()>1)){
        equation = equation.replace(getOp(equation),Op(getOp(equation)).replace(',', '.'));
        equation = RemoveNegative(equation);
        System.out.println(equation);
    }
    System.out.println("soustraction:" +equation);

}

public static String getOp(String s){
    String r ="";
    if(s.contains("/")){
        int slash = s.indexOf("/");
        int first = slash;
        int last = slash;
        first -= 1;
        while((first >= 0)&&(s.charAt(first) != '+')&(s.charAt(first) != '-')&(s.charAt(first) != '*')&(s.charAt(first) != '/')){
            first -= 1;
        }
        first += 1;
        last += 1;
        while((last < s.length())&&(s.charAt(last) != '+')&(s.charAt(last) != '-')&(s.charAt(last) != '*')&(s.charAt(last) != '/')&&(s.charAt(last) != '/')){//&(last >= s.length())
            if(last < s.length()) {
                last += 1;
            }
        }
        r = s.substring(first,last);
    }
    else if(s.contains("*")){
        int slash = s.indexOf("*");
        int first = slash;
        int last = slash;
        first -= 1;
        while((first >= 0)&&(s.charAt(first) != '+')&(s.charAt(first) != '-')&(s.charAt(first) != '*')&(s.charAt(first) != '/')){
            first -= 1;
        }
        first += 1;
        last += 1;
        while((last < s.length())&&(s.charAt(last) != '+')&&(s.charAt(last) != '-')&&(s.charAt(last) != '*')&&(s.charAt(last) != '/')){
            if(last < s.length()) {
                last += 1;
            }
        }
        r = s.substring(first,last);
    }
    else if(s.contains("+")){
        int slash = s.indexOf("+");
        int first = slash;
        int last = slash;
        first -= 1;
        while((first >= 0)&&(s.charAt(first) != '+')&(s.charAt(first) != '-')&(s.charAt(first) != '*')&(s.charAt(first) != '/')){
            first -= 1;
        }
        first += 1;
        last += 1;
        while((last < s.length())&&(s.charAt(last) != '+')&&(s.charAt(last) != '-')&&(s.charAt(last) != '*')&&(s.charAt(last) != '/')){
            if(last < s.length()) {
                last += 1;
            }
        }
        r = s.substring(first,last);
    }
    else if(s.contains("-")){
        int slash = s.indexOf("-");
        int first = slash;
        int last = slash;
        first -= 1;
        while((first >= 0)&&(s.charAt(first) != '+')&(s.charAt(first) != '-')&(s.charAt(first) != '*')&(s.charAt(first) != '/')){
            first -= 1;
        }
        first += 1;
        last += 1;
        while((last < s.length())&&(s.charAt(last) != '+')&&(s.charAt(last) != '-')&&(s.charAt(last) != '*')&&(s.charAt(last) != '/')){
            if(last < s.length()) {
                last += 1;
            }
        }
        r = s.substring(first,last);
    }

    return r;
}


public static String RemoveNegative(String s){
    s = s.replace("-+","-");
    s = s.replace("+-","-");
    if(s.charAt(0) == '-'){
        s = s.replaceFirst("-","");
        s = s.replace("-","+");
        while(s.contains("+")){
            s = s.replace(getOp(s),Op(getOp(s)));
        }
        s = "-"+s;
    }
    return s;
}

}


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接