On the internet to see a very strong method of implementation, the use of recursion.
/*** Ideas * 1, exclude empty string * 2, get index of the first symbol * 3, if there is only a number, direct conversion and return * 4, if there is an opening parenthesis, then find the right parenthesis, and the parentheses inside the string is calculated recursively, and for Change, and then the overall recursion, remove all brackets * 5, the first recursive decomposition plus minus, to ensure that the priority of multiplication * 6, and then recursive decomposition multiplication, multiplication calculated after the calculation will automatically add and subtract *@paramS *@return * @throwsException*/ Public Static floatOpt (String s)throwsexception{//1 if(s = =NULL|| "". Equals (S.trim ())) { return0f; } //2 intA1=s.indexof (' + ')); intA2=s.indexof ('-'); intA3=s.indexof (' * ')); intA4=s.indexof ('/'); intA5=s.indexof (' ('); //3 Calculating the individual numbers if(A1==-1&&a2==-1&&a3==-1&&a4==-1){ if(S.trim () = =NULL||"". Equals (S.trim ())) { Throw NewException ("Operate error"); } returnfloat.parsefloat (S.trim ()); } //4 parentheses are calculated first if(A5!=-1){ intA6=s.lastindexof (') '); if(A6==-1){ Throw NewException ("Parentheses do not match"); }Else{ floatF=opt (S.substring (a5+1, A6). Trim ()); S=s.replace (S.substring (a5,a6+1), string.valueof (f)); returnopt (s); } } //5 first add and subtract to ensure the priority of multiplication if(A1!=-1){ returnOpt (s.substring (0,A1)) +opt (S.substring (a1+1, S.length ())); } if(A2!=-1){ returnOpt (s.substring (0,A2))-opt (S.substring (a2+1, S.length ())); } //6 if(A3!=-1){ returnOpt (s.substring (0,A3)) *opt (S.substring (a3+1, S.length ())); } if(A4!=-1){ returnOpt (s.substring (0,A4))/opt (S.substring (a4+1, S.length ())); } returnInteger.parseint (S.trim ()); }
There is also a more convenient way to take advantage of the built-in JS engine
Public Static Object jscalculate (String script) { new Scriptenginemanager (); = Manager.getenginebyname ("javascript"); Try { return (Object) engine.eval (script); Catch (Scriptexception ex) { ex.printstacktrace (); } return NULL ; }
Java implementation of simple arithmetic expressions (2)