java - how to validate an arithmetic expression? -


i have program ask user input arithmetic expression, how can validate expression. example: user input"1.2+3.4*(3.2+2.3)-12.1/3.4", output same expression cause valid. if user input "/1.2", invalid input, please enter right expression. "* 1.2","1.2**3.4","1.2//3.4",and "1.2 + * 3.4" consider invalid. however,"-3+4","3++4","3*+4",and"3+-6"are consider valid. please me.

here have far.

private static boolean validate(string s) {      if (s.isempty()) {          return false;     } else {        // remove spaces        s = s.replaceall("\\s+", "");        // remove repeated char        // check if string contains numbers , +-*/        string validchars = "+-*/().1234567890";        boolean result = true;        (char c : s.tochararray()) {            if (validchars.indexof(c) == -1) {                result = false;            }        }         return result;     }  }  

you can use script engine manager class of import javax.script.* .

scriptenginemanager manager = new scriptenginemanager(); scriptengine engine = manager.getenginebyname("javascript"); 

now have evaluate expression this.

engine.eval(expression);//where expression string in case user input 

but surround try-catch because if expression not valid through scriptexception.

so if exception means it's not valid expression.


Comments

Popular posts from this blog

user interface - How to replace the Python logo in a Tkinter-based Python GUI app? -

objective c - Greedy NSProgressIndicator Allocation -

how to set an OCR language in Google Drive -