Frage

I'm trying to write a method that does addition, and subtraction

using indexOf() , lastIndexOf()

for example string s = "3 + 3" I want to break this string into two substrings then do certain operation.

// 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.

War es hilfreich?

Lösung

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.

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

Andere Tipps

what you could do is, first to go through your string, and doo operations arthmetics (ie "1+-1" -> "1-1", "1--1" -> "1+1" etc) then work with operations

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.

Use the 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

OR

Use 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

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top