简体   繁体   English

Java:计算器,BNF,AST加法和减法

[英]java: calculator, BNF, AST adding & subtracting

I'm trying to write a method that does addition, and subtraction 我正在尝试编写一种可以进行加法和减法的方法

using indexOf() , lastIndexOf() 使用indexOf(),lastIndexOf()

for example string s = "3 + 3" I want to break this string into two substrings then do certain operation. 例如字符串s =“ 3 + 3”,我想将此字符串分成两个子字符串,然后执行某些操作。

// for addition
String s = "3 + 3";
int indexOfPlus = s.indexOf('+');

String beforePlus = s.substring(0,indexOfPlus);
String afterPlus= s.substring(indexOfPlus+1);
 .....
 .....

// for subtraction
String s = "3 - 3";
int indexOfMinus = s.indexOf('-');

String beforeMinus = s.substring(0,indexOfMinus);
String afterMinus = s.substring(indexOfMinus+1);

 ....
 ....

My QUESTION IS: However, I'm not sure how should I break the string such as "3+ -1" or "3- +1" into substrings. 我的问题是:但是,我不确定如何将诸如“ 3+ -1”或“ 3- +1”之类的字符串分成子字符串。

您可以做的是,首先遍历字符串,然后进行doo操作关节(例如“ 1 + -1”->“ 1-1”,“ 1--1”->“ 1 + 1”等),然后开始工作与操作

I would treat each of + and - as two different operators, a binary operator and a unary operator. 我会将+和-分别视为两个不同的运算符,即二进制运算符和一元运算符。 If you see a "-" at the start of an expression, or after another operator, it is unary-. 如果在表达式的开头或另一个运算符之后看到“-”,则为一元-。 If you see it between two expressions, it is binary-. 如果在两个表达式之间看到它,则为二进制。 In AST form, unary- has one child, binary- has two children. 以AST形式,一元-有一个孩子,二元-有两个孩子。

first of all I would advise to use separate fields for each operand and operation, that way you won't have to split anything and just parse the numbers. 首先,我建议为每个操作数和操作使用单独的字段,这样您就不必拆分任何内容而只需解析数字。

there is something called regex, although it's a little advanced it will enable you to do these operations much easier using the method String.split() , this method takes a regex as a parameter and returns the splitted strings as array, for instance ("5+5").split("[-+]") will return 5 and 5 each as a String. 有一种叫做regex的东西,尽管它稍微先进一点,但是它使您可以使用String.split()方法更轻松地执行这些操作,该方法将regex作为参数,并将分割后的字符串作为数组返回,例如(“ 5 + 5“)。split(” [-+]“)将分别以字符串形式返回5和5。

using indexOf only I would do something like this (for "3- +1"):

int i1,i2;
String op;
i1 = s.indexOf("-");
i2= s.indexOf("+");
if ( i1<0 || i2<0)
   //only one operation
else if(i1<i2)
   //minus logic;
else if (i2<i1)
   // plus logic

Use the javax.script.ScriptEngineManager: 使用javax.script.ScriptEngineManager:

ScriptEngineManager manager = new ScriptEngineManager();

 ScriptEngine engine = manager.getEngineByName("js");<br> Object result = engine.eval("3+ -4");<br> System.out.println(result);<br> 

OUTPUT: -1.0 输出:-1.0

OR 要么

Use BeanShell http://www.beanshell.org/download.html 使用BeanShell http://www.beanshell.org/download.html
Interpreter interpreter = new Interpreter();

 interpreter.eval("result = 3+-4");<br> System.out.println(interpreter.get("result"));<br> 

OUTPUT: -1 输出:-1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM