Search code examples
javasubstringabstract-syntax-treeindexofbnf

java: calculator, BNF, AST adding & subtracting


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.


Solution

  • 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