Given a formula string to disassemble and calculate the result in Java

Source: Internet
Author: User

The requirements are simple, given a formula rule in the form of a string, disassembled with Java code, and the results can be computed.

Consider the number format "Integer, Decimal," in a string

? Consider the operator "+-*/()" in the string

? Consider the space, the arithmetic rule "divide by 0"

The following is the reference address, which contains the contents of the discussion section:

https://bbs.csdn.net/topics/380022283

Below is the Code section, which can be used as a tool class:

 Packagetest;Importjava.util.ArrayList;ImportJava.util.Comparator;Importjava.util.List;ImportJava.util.Stack;/*** Given formula string disassembly calculation *@authorKerala **/ Public classCalutil {Static FinalString symbol = "+-*/()";//operator    Static FinalString[] Priority = {"+-", "*/", "()"};//Operator Precedence         /*** Operator Comparator*/    StaticComparator<string> Comp =NewComparator<string>() {         Public intCompare (string s1, string s2) {intN1=0, n2=0;  for(inti=0; i<priority.length; i++) {                if(Priority[i].indexof (S1) >= 0) {N1 =i;} if(Priority[i].indexof (S2) >= 0) {N2 =i;} }            return(N1-n2);      }    }; /*** Input string formula, return result *@paramExp *@return   * @throwsException*/     Public StaticString getresultbystrcal (String exp)throwsexception{List<String> list = analyze (exp);//infix suffix        Doubleresult = CAcl (list);//Calculation Results        returnString.Format ("%.2f", result);//%.2f\n Explanation:%f--floating point type. 2--two-bit decimal point \n--line break    }    /*** Analysis Formula *@paramExp *@return     * @throwsException*/     Public Staticlist<string> analyze (String exp)throwsException {if(exp = =NULL) {            Throw NewException ("Illegal parameter."); } exp= Exp.replaceall ("\\s*", "");//Remove all spaces (to facilitate the existence of space in the middle of the legal)List<String> list =NewArraylist<string>(); Stack<String> sym =NewStack<string>(); StringBuilder buf=NewStringBuilder ();  for(CharC:exp.tochararray ()) {            if(Symbol.indexof (c) >= 0) {//if the operator                if(Buf.length () > 0) {//if there are operandsString v =buf.tostring (); if(! v.matches ("\\d+ ([.] \\d+)? ")) {                        Throw NewException ("Illegal varaible (" +v+ ").");                    } list.add (v); Buf.delete (0, Buf.length ()); }                if(c = = ' (') {Sym.push (string.valueof (c)); } Else if(c = = ') ') {String last= "";  while(Sym.size () > 0) { last=Sym.pop (); if(Last.equals ("(")) {                             Break; } Else{list.add (last); }                    }                    if(!" (". Equals (last)) {                        Throw NewException ("Illigal Express."); }                } Else if(Sym.size () > 0) {String s=string.valueof (c); String Last=Sym.peek (); if(Last.equals (") | | Comp.compare (S, last) > 0) {Sym.push (s); } Else{ Last=Sym.pop ();                        List.add (last);                    Sym.push (s); }                } Else{Sym.push (string.valueof (c)); }                     } Else{//not an operator is treated as an operand (because all spaces have been removed, it is no longer necessary to determine the space)Buf.append (c); }        }        if(Buf.length () > 0) {List.add (buf.tostring ()); }         while(Sym.size () > 0) {String last=Sym.pop (); if("()". IndexOf (last) >= 0) {                Throw NewException ("Illigal Express.");        } list.add (last); }                returnlist; }    /*** Calculation *@paramlist *@return     * @throwsException*/     Public Static DoubleCAcl (list<string> List)throwsException {Stack<Double> val =NewStack<double>(); Doubleresult = 0;  while(List.size () > 0) {String s= List.remove (0); if(Symbol.indexof (s) >= 0) {                DoubleD1 =Val.pop (); DoubleD2 =Val.pop (); if("+". Equals (s)) {Result= D2 +D1; } Else if("-". Equals (s)) {Result= D2-D1; } Else if("*". Equals (s)) {Result= D2 *D1; } Else if("/". Equals (s)) {Result= D2/D1; } Else {                    Throw NewException ("Illigal symbol" ("+s+"). ");            } val.push (Result); } Else {                if(!s.matches ("\\d+ ([.] \\d+)? ")) {                    Throw NewException ("Illigal variable (" +s+ ").");            } Val.push (Double.valueof (s)); }        }                returnresult; }    }

Test it:

 Packagetest;/*** Test Split string formula operation *@authorKerala **/ Public classtestcal {/**     * @paramargs *@throwsException*/     Public Static voidMain (string[] args) {String exp= "2.5*0.4+ (2*5)"; Try{String result=calutil.getresultbystrcal (exp);        System.out.printf (result); } Catch(Exception e) {e.printstacktrace (); System.out.println ("Please enter the correct calculation formula"); }            }}

Currently testing a few formulas, are also correct, if there are problems, then add!

Given a formula string to disassemble and calculate the result in Java

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.