Arithmetic code (Java version) with regular expressions

Source: Internet
Author: User
Tags arithmetic

Subtraction negative numbers, brackets, and several
See the Code and Comments (test did not find the bug, such as found a bug, please correct me)


 Packagecom.test;Importjava.util.ArrayList;Importjava.util.List;ImportJava.util.regex.Matcher;ImportJava.util.regex.Pattern;/*** Arithmetic, may not be the best way of writing, their own test did not find bug<br> * Premise: The correct formula, because did not do the verification of the formula <br> * Ideas:<br> * 1, with regular split all the elements of the example: 2-5+4*5/( 2) -4<br> * split into "2,-5,4,*,5,/, (, 2, 2,), 4" <br> * 2, calculate parentheses first, multiplication, last add minus * * Summary: Total spent 17, 8 hours, the main reason is not careful overall analysis process caused. <br> * So that the idea of the point of writing code, revision changes, not a complete grasp of the idea. So a problem must be <br> * First walk through the whole idea, the process is actually coding is the easiest, the focus is the process of thinking * *@authorWangshiyan * @time 2014-12-4 pm 12:50:01 **/ Public classSizhetool { Public Static voidMain (string[] args) {Try{System.out.println (Jisuanstr ("11.2+3.1* (423-(2+5.7*3.4) +5.6) -6.4/(15.5+24)")); } Catch(Exception e) {System.out.println ("Please check your calculation format");        E.printstacktrace (); }    }    /*** Split the various elements in the calculation and handle the corresponding position <br> * *@paramSTR *@return     */     Public StaticList<string> splitstr (String string)throwsException {List<String> Listsplit =NewArraylist<string>(); Matcher Matcher= Pattern.compile ("\\-?\\d+ (\\.\\d+)? | [*/()]|\\-"). Matcher (string);//split into each element with a regular         while(Matcher.find ()) {//System.out.println (matcher.group (0));Listsplit.add (Matcher.group (0)); }        returnListsplit; }    /*** Calculation <br> * Steps: 1, if there are brackets <br> * then take the previous nearest (coordinate calculation of the current parentheses in the formula), continue to look for parentheses and so on, until the loop uses all the coordinate elements * calculation Complete (Operation order parentheses, multiplication, plus minus) * *@paramSTR *@return     */     Public Static DoubleJISUANSTR (String str)throwsException {Doublereturndouble = 0; List<String> listsplit = splitstr (str);//split the good elementsList<integer> zkuohaoidxlist =NewArraylist<integer> ();//left parenthesis,< coordinates,>        if(Pattern.compile (". *\\ (|\\). *"). Matcher (str). FIND ()) {//If you include the parentheses operationString value = "";//Single character value            intZidx = 0;//Subscript of the last left parenthesis in zkuohaoidxlist//this layer loops through all the calculations in parenthesesList<string> templist =NewArraylist<string> ();//elements that are not previously evaluated            intRemovel = 0; intTemplistsize = 0;  for(inti = 0; I < listsplit.size (); i++) {Value=Listsplit.get (i);                Templist.add (value); Templistsize=templist.size (); if((". Equals (value)") {//opening parenthesisZkuohaoidxlist.add (tempListSize-1); } Else if(")". Equals (value)) {//computes the calculation with the closing parenthesis between the previous opening parenthesisZidx = Zkuohaoidxlist.size ()-1;//match the nearest left parenthesis to the current closing parenthesis                    intStart =Zkuohaoidxlist.get (ZIDX); Returndouble= Jisuan (templist, start + 1, tempListSize-1);//start position, which is the last left parenthesisRemovel = Templistsize-start; Templist= Removeuselist (templist, removel);//remove an already used elementTemplist.add (returndouble + "");//just calculate the value to add inZkuohaoidxlist.remove (ZIDX);//finish calculation Clear parentheses                }            }            //finish all the calculations .returndouble = Jisuan (templist, 0, Templist.size ()); } Else{//no parentheses Operationreturndouble = Jisuan (listsplit, 0, Listsplit.size ()); }        returnreturndouble; }    /*** Reverse deletion of used elements * *@paramlist *@paramremovelength * Quantity *@return     */     Public StaticList<string> removeuselist (list<string> List,intremovelength) {        intLe = List.size ()-removelength;  for(inti = List.size ()-1; I >= le; i--) {list.remove (i); }        returnlist; }    /*** Calculation Formula * *@paramListsplit *@paramStart * Bracket calculation start position *@paramEnd * Bracket Terminator position *@return     */     Public Static DoubleJisuan (list<string> Listsplit,intStartintend)throwsException {Doublereturnvalue = 0; String strvalue=NULL;//Temp VariableList<string> jjvaluelist =NewArraylist<string> ();//the remaining plus and minus elements//Traverse Calculation Multiplication Method         for(inti = start; I < end; i++) {strvalue=Listsplit.get (i); if("*". Equals (strvalue) | | "/". Equals (strvalue)) {//multiplicationstrvalue = Jisuanvalue ("*". Equals (strvalue)? "*" : "/", Double. Parsedouble (Jjvaluelist.get (jjvaluelist.size ()-1)), double.parsedouble (Listsplit.get (i+ 1)))                        + ""; Jjvaluelist.remove (Jjvaluelist.size ()-1); I++;        } jjvaluelist.add (strvalue); }        //traverse calculation plus minus         for(intj = 0; J < Jjvaluelist.size (); J + +) {strvalue=Jjvaluelist.get (j); if("-". Equals (strvalue) | | "+". Equals (strvalue)) {returnvalue= Jisuanvalue ("-". Equals (strvalue)? "-" : "+", ReturnValue, Double.parsedouble (Jjvaluelist.get (J+ 1))); J++; } Else{returnvalue+=double.parsedouble (Jjvaluelist.get (j)); }        }        returnreturnvalue; }    /*** Calculate the subtraction operation of 2 numbers such as: 2*5, 2/5 * *@paramtype * operator *@paramstart * Number equals above 2 *@paramend * is counted equivalent to 5 above *@return     */     Public Static DoubleJisuanvalue (String type,DoubleStartDoubleend)throwsException {Doubled = 0; if("-". Equals (Type) {D= Start-end; } Else if("+". Equals (Type) {D= Start +end; } Else if("*". Equals (Type) {D= Start *end; } Else if("/". Equals (Type) {            if(0 = = Start | | 0 = =end) d= 0; ElseD= Start/end; }        returnD; }}




Arithmetic code (Java version) with regular expressions

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.