0

I have some mathematical expressions as Java Strings (100 % 6)* 7 = and Sin(45) + log 100 – 3 ^ 5 =. I want to parse these on operands and operators then solve them.

But I don't want to use Java Regular Expressions. What is the best solution?

Lisa
  • 4,333
  • 2
  • 27
  • 34
Ehsan
  • 2,273
  • 8
  • 36
  • 70
  • It's not 'splitting', it's called 'scanning' (or 'tokenizing') and 'parsing'. – user207421 Oct 24 '13 at 04:10
  • @EJP tahnk you, I just edited it – Ehsan Oct 24 '13 at 04:12
  • So you need a parsing technology that you can access from java. There are questions that already ask and answer this question. http://stackoverflow.com/questions/1792261/java-maths-parsing-api – Lisa Oct 24 '13 at 04:30

2 Answers2

1

bison+yacc may be what you want, a LALR text parser.

afpro
  • 1,103
  • 7
  • 12
  • I'd recommend two Java-based solutions: ANTLR or JavaCC. The former is more modern and better supported today. – duffymo Oct 24 '13 at 11:49
1
import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;

public class aaa {



     public static void main(String []args){

        try {


        String xyz = "3*3+3";
        String kkk = "(100 % 6)* 7";

        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine se = manager.getEngineByName("JavaScript");        
        Object result1 = se.eval(xyz);
        Object result2 = se.eval(kkk);


        System.out.println("result1: "+result1);
        System.out.println("result2: "+result2);


        } 
        catch (Exception e) {
         e.printStackTrace();
        }
     }

}
Teddybugs
  • 1,232
  • 1
  • 12
  • 37
  • 1
    It using JavaScript engine but I want to process in JAVA and it cant calculate sin and log – Ehsan Oct 24 '13 at 04:36
  • 1
    Mere code is not an answer at SO. You have to explain. – user207421 Oct 24 '13 at 04:41
  • This is Java code. Rhino is built into Java. I disagree with EJP - code is perfectly okay. Do what you can. You wouldn't chide Jon Skeet if he posted code. – duffymo Oct 24 '13 at 11:43