在Java中将字符串转换为运算符(+ */-) [英] Convert String to operator(+*/-) in java

查看:2140
本文介绍了在Java中将字符串转换为运算符(+ */-)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Stack类来计算涉及整数的简单算术表达式, 例如1 + 2 * 3.您的程序将按照给定的顺序执行操作,而与运算符的优先级无关. *因此,应计算表达式1 + 2 * 3(1 + 2)* 3 = 9,而不是1+(2 * 3)= 7.

I am using Stack class to calculate simple arithmetic expressions involving integers, such as 1+2*3.your program would execute operations in the order given,without regarding to the precedence of operators. *Thus, the expression 1+2*3 should be calculated (1+2)*3=9,not 1+(2*3)=7.

如果输入为1 + 2 * 3,我知道如何将字符串1,2,3转换为Integer.但是我不知道如何将+,*从字符串类型转换为运算符.

If i get the input as 1+2*3,i know how to convert the string 1,2,3 to Integer.but i don't know how to covert +,* from string type to operator.

我的代码逻辑是: 例如:给定字符串2 +(3 * 5),因此将首先操作3 * 5,然后在3 * 5的结果中执行+2.

My code logic is: For eg: Given string 2 + (3 * 5), So 3 * 5 will be operated first then +2 will be performed in result of 3 * 5.

推荐答案

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

probably the best way to do it will be equals, but it's best to ignore whitespaces:

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

i'm not quite sure how you split your string, but for example, if you have a char op and two integer a and b:

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

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

这篇关于在Java中将字符串转换为运算符(+ */-)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆