Recently, I checked the Internet recently, but I didn't find the code for the four operations written by Java, so I lower it. If you have any questions, please give feedback.
1. Explanation
The code only achieves a simple four operations, supports+,-,*,/, (, (,) can only calculate the correct expression value, and there is no verification of illegal expression.
2. Implementation method
Step 1: Convert the input string to List, which is mainly used to convert string into atoms: value/operator/bracket
Public list trans much (string str) {list strlist = new arrayList ();/* Get the symbol strings of the data*/string tmp = str.replaceall ("// d*", "");/* record the current calculation Faculty*/ String Curlet = NULL;/*Record the position of the first operator in the tmp character*/ int Loc = 0;/*symbol strings*/ int len = tmp.length (); for (int i = 0; I <len; I ++) {curlet = tmp.substring (i, i+1); loc = str.indexof (curlet); / * (Str.substring (0, LOC) .trim ())) {strist.add (str.substring (0, loc) .trim ());} strlist.add (str.substring (LOC, LOC + 1)) ; str = str.substring (LOC + 1);} if (0 <STR.Length ()) {strlist.add (str.trim ());} Return Strlist;}
Step 2: Convert the original medium -colored expression to the suffix expression. In four operations, the suffix expression is the most convenient calculation
public string [] midtoend (list midlist) {stack embl = new stack (); stack result = new stack (); iterator it = midlist.iterator (); string cressr = null; While (it.hasnext ()) {cursstr = (String) it.next(); /* Confirm whether the string is formal */ if(sign.containsKey(curStr))) { /* If the symbol stack is empty or the symbol is ( */ if (0 == embl.size () || "(" .equals (CURSTR)) {Embl.push (CURSTR);} Else { /*If the symbol is) The symbol stack needs to be out of the stack until one (so far* / if (")". (CURSTR) {While (! "(" (". Equals ((String) Embl.peek ())) {if (0> = embl.size ()) {Return null;} result.push (embl.pop ()) );} Embl.pop ();} Else {int P1 = Integer.parseint ((String) Sign.get (CURSTR)); int P2 = Integer.parseint ((String) Sign.get (Embl.peek ()) ); /* If the priority of the current character is greater than the priority of the top symbol of the stack* / if (P1> P2) {Embl.push (CURSTR);} Else {While (P1 <= P2 || Embl.size ()> 0) {result.push (embl.pop ()); if (0 == Embl.size ()) {Break;} p2 = Integer.parseint ((String) sign.get (Embl.peek ())); } Embl.push (CRSTR);}}}} Else {result.push (curstr);} while (0 <embl.size ()) {result.push (embl.pop ());} int len = result .size (); string [] reT = New String [len]; for (int i = 0; i <len; i ++) {Ret [Len -i -1] = (string) result.pop ();} Return RET;}
Step 3: The final result of the analysis of the suffix expression, returning the calculation of the calculation
/** * Parses the suffix expression and returns the corresponding operation result* @param String[] endStr The converted suffix expression* @return Object Return the operation result If the expression is incorrect, print "Input Error" directly */ public Object calculate (String[] endStr) { int len = endStr.length; Stack calc = new Stack(); double p2; double p1; for (int i = 0; i < len; i++) { if (sign.containsKey(endSt R [ i]) {Try {p2 = double.parsed allowance (string) callc.pop ()); (P1 , p2, endstr [i]))));} Catch (NumberForMatexception EX) {ex.printstacktrace (); Return "Input Error";} Catch (Exception ex) {ex.printstacktrace (). ; Return "input error";} } Else {Calc.push (Endstr [i]);}}} if (1 == Calc.size ()) {Return Calc.pop ();} Else {Return "Input Error";} /*** Implementation The underlying operation function* @param double p1 Number 1 * @param double p1 Number 2 * @param String operator +-/* */ public double simpleCalc(double p1, double p2, String operator) { swit ch (open.charat (0)) {case ' +': return p1 + p2; case ' -': return p1 -p2; case ' *': return p1 * p2; case ' /': reTurn p1 / p2; }}
Step 4: The priority of the operator is placed in the cache for extraction
private static HashMap sign = new HashMap(); /* Put the operator's priority into cache processing*/ public CalculateExp() { sign.put(")", "3"); sign.put("*" , "2"); sign.put ("/", "2"); sign.put ("+", "1"); sign.put ("-", "1"); sign.put ("" ("," 0 ");}
Complete code
Import java.util.arrayList; Import Java.util.hashmap; Import Java.util.itrator; Import Java.util.list; Import java.util.stack;/*** java implementation Counting expression* Only achieved addition and subtraction Multiplication and division and bracket operations* For example: 3+12+25*(20-20/4)+10 * @author GuoBo 2009-3-16 * @version 1.0 */public class CalculateExp{private static HashMap sign = new H ashmap ( );/*Put the priority of the operator into the cache processing*/public calling () {sign.put (")," 3 "); sign.put ("*"," 2 "); sign. put ("/", "2"); sign.put ("+", "1"); sign.put ("-", "1"); sign.put ("(" ("," 0 "); }/** * @param String The input expression* @return List parsed string element* Parsing the input string* Convert to data that needs to be processed* For example: 3+12+25*(20-20 /4) +10 * The result of the conversion is: * list element is RET = {3,+,+, 25, *, (, 20, 20, 20,//, 4, 4,),+ ,10} */public List transStr(String str){List strList = new ArrayList();/* Get the symbol string of the proposed data*/String tmp = str.replaceAll("//d*", "");/ * Record the current operator*/String curLet = null;/* Record the position of the first operator in the tmp string*/int loc = 0;/* Symbol string length*/int len = tmp.length(); For (int i = 0; I <len; i ++) {curlet = tmp.substring (i, i+1); local = str.indexof (curlet);/ * If the current processing character is (or) */if () "". Equals (str.substring (0, loc) .trim ())) {strist.add (str.substring (0, local) .trim ());} strlist.add (str.substring (LOC, LOC, LOC, LOC, LOC, LOC, LOC, LOC + 1); str = str.substring (loc + 1);} if (0 <STR.Length ()) {strlist.add (str.trim ());} Return Strlist;}/*** will Convert expressions from infix expressions to suffix expressions (Polish) * @Param List List of parsed expressions* @return String[] Converted expression string array*/public String[] midToEnd(List midList ) {Stack embl = new stack (); stack result = new stack (); Iterator it = midlist.iterator (); string cursstr = null; space Ring) IT.NEXT ( );/* Confirm whether the format string*/if (sign.containskey (curstr)) {/* If the symbol stack is empty or the symbol is (*/if (0 == embl.size () || "(". ". Equals (CURSTR)) {Embl.push (CURSTR);} Else {/*If the symbol is) The symbol stack needs to be out of the stack until one (so far*/if (")". Equals (CURSTR)) {While (!! "(" (".equals ((string) embl.peek ())) {if (0> = embl.size ()) {reTurn null;} result.push (emBl.pop ()));} embl.pop () ;} Else {int P1 = Integer.parseint ((String) Sign.get (CURSTR)); int P2 = Integer.parseint ((String) Sign.get (Embl.peek ()));/* If the current character's current character Priority of priority than the top symbol of the stack*/if (P1> P2) {Embl.push (CURSTR);} Else {While (P1 <= P2 || Embl.size ()> 0) {Result.push (EMBL .pop ()); if (0 == Embl.size ()) {Break;} p2 = Integer.parseint ((String) sign.get (Embl.peek ()));} Embl.push (CURSTR); }}} Else {Result.push (CURSTR);} While (0 <embl.size ()) {result.push (embl.pop ());} int len = result.size (); string [] RET = New String [Len]; for (int i = 0; I <len; I ++) {RET [Len -i -1] = (String) Result.pop ();} Return Ret;}/*** Analysis Suffix expression, return the corresponding operation result* @param String[] endStr The converted suffix expression* @return Object Return the operation result If the expression is incorrect, print "Input Error" */public Object calculate(String[] endStr ) {int len = endstr.Length; stack call = new stack (); double p2; double p1; for (int i = 0; i <len; i ++) {if (sign.containskey (endstr [i]))) {) { Try {p2 = double.parsed allowance (string) callc.pop ()); p1 = double.parsed allowance ((string) callc.pop ()); Endstr [ i]));} Catch (NumberFormatexception EX) {ex.printstacktrace (); Return "input error";} Catch (Exception Ex) {ex.printstacktrace (); put error ";}} Else {Calc. push (endstr [i]);}} if (1 == Calc.size ()) {Return Calc.pop ();} Else {Return "Input Error";}/*** realize the underlying computing function* @param double p1 Number 1 * @param double p1 Number 2 * @param String operator +-/* */public double simpleCalc(double p1, double p2, String operator){switch(oper.char At (0)) {{ Case ' +': Return P1 + P2; Case ' -': Return P1 -P2; Case '*': Return P1*P2; CASE '/': Return P1/P2; Default: Return P1;}/** *Main control function*/place static void main (string [] args) {Calculatexp CE = New CalculatingExp (); String TMP = "3+12+25*(20-20/4+10"; String Ret = (String Ret = (String ing ) ce.calculate(ce.midToEnd(ce.transStr(tmp)));double value = 0; try { value = Double.parseDouble(ret); } catch (NumberFormatException ex) { Systeme m.out.print (RET); } System.out.print (value);}}
The following is a supplement from other netizens
The idea of code is to calculate each minimum calculation unit through regular judgment. The following is the code:
import java.math.BigDecimal;import java.util.regex.Matcher;import java.util.regex.Pattern;/** * Calculator tool class* @author shuqi * @date 2015-7-23 * @ version since 1.0 */Public Class Calculatorutil {Public Static BigDeCimal Arithmetic (String Exp) {if (! Exp.matic ("// D+") {String Result = PARSEEXP (Exp) .re placeall ("[// [//]]" "" , ""); Return New Bigdecimal (Result);} Else {Return New Bigdecimal (exp);}/*** minimum counting unit***/private string = "^^((// d+((// d+(// d+ //. //d+))izing (//.//d+)?)|(//[//-//d+(//.//d+)?//]))$"; /** * Operation without brackets*/ private Static String Notarentheses = "^^// (//)]+$";/*** matching multiplication or division method*/private string prioroperatorexp = "((// d+(//.// d+)? ) | (//-- // d+(//.// d+)? //]) [//*///] (// d+(//.// d+)?) | (// [//d+ (/////d+)?///])) "/*** matching addition and subtraction*/private string operatorexp =" //./d+))||-1 (/////d+ //d+ off .//d+))|-1 (////-/d+ (// //d+)?////////////////////////dmi))) ")") ")"; minparentheses = "// ([^// (//)]+//)";/*** Analyze and calculate the four operations expressions, for example: 2+((3+4)* 2-22)/2* 3 * @param expression * @return */ private static String parseExp(String expression){ //The method enters and replaces the space first, and removes the () number on both sides of the operation expression=expression.replaceAll("//s +"," ") .replaceall ("^// (([^// (/)]+) //) $", "$ 1"); // minimum expression calculation if (expression.matches (minexp)) {string result = calculate(expression); return Double.parseDouble(result)>=0?result:"["+result+"]"; } // Calculate four operations without brackets if(expression.matches(noParenthes ES)) {pattern patt = Pattern.compile(priorOperatorExp); Matcher mat=patt.matcher(expression); if(mat.find()){ String tempMinExp=mat.group(); expression=expression.replace First (Prioroperatorexp, PARSEEEXP (Tempminexp));} else{ patt=Pattern.compile(operatorExp); mat=patt.matcher(expression); if(mat.find()){ String tempMinExp=mat.group(); expression=expression.repla CEFIRST (OperatorXP, PARSEEXP (TempmineXP) ); } } return parseExp(expression); } // Calculate four operations with brackets Pattern pattern=Pattern.compile(minParentheses); Matcher mat=patt.matcher(expression); if(mat.find( )) {String TempmineXP =mat.group(); expression=expression.replaceFirst(minParentheses, parseExp(tempMinExp)); } return parseExp(expression); } /** * Calculate the minimum unit four operation table Day (two numbers) * @param exp * @Return */Private Static String Calculating (String Exp) {Exp = Exp.replaceall ("[// [/]" "," "); String Number [] = Exp.replacefirst (" (// d) [[// d) [[" //+//-//*///] "," $ 1, "). Split (", ","); BigDecimal Number1 = New BigDeCimal (Number [0]); Bigdecimal Number2 = New BigdeCimal (Number [1] );; String Operator = Exp.replacefirst ("^^.*// D ([///////////////bus", "$ 1"), +".equals(operator)){ result=number1.add(number2); }else if("-".equals(operator)){ result=number1.subtract(number2); }else if("*". equals (operator)){ result=number1.multiply(number2); }else if("/".equals(operator)){ //The second parameter is precision, and the third is the four-color five-entry mode result=number1 .divide(number2,5,BigDecimal.ROUND_CEILING); } return result!=null?result.toString():null; } }
The code was originally a blog, but the code had no comments and there was a bug. I revised it a little and added comments. Take a note here for easy use later
In addition, to express respect to the original author, the original code is attached
/** * Four operation expression calculation* @author penli * */public class Arithmetic { public static void main(String args[]){ System.out.println(arithmetic("2.2+( (3+4)*2 -22)/2*3.2")); } public static double arithmetic(String exp){ String result = parseExp(exp).replaceAll("[//[//]]", ""); return Double.parseD ouble (result); } /** * Analytical calculation of four operation expressions, example: 2+((3+4)*2-22)/2*3 * @param expression * @return */ public static String parseExp(String expression){ //String numberReg="^((?!0)//d+(//.//d+(?<!0))?)|(0//.//d+(?<!0) )$"; expression=expression.replaceAll("//s+", "").replaceAll("^//((.+)//)$", "$1"); String checkExp="//d" ; String minExp="^((//d+(//.//d+)?)|(//[//-//d+(//.//d+)?//]))[//+ //-//*//]((//d+(//.//d+)?)|(//[//-//d+(//.//d+)?//]))) $ "; // The minimum expression calculation if (expression.matches (minexp)) {string res) ult+"]"; } //Calculate four operations without brackets String noParentheses="^[^//(//)]+$"; String priorOperatorExp="(((//d+(//.//d+)?)|(/ /[//-// d+(//.// d+)? //]) [//*///] (// d+(//.// d+)?) | (// ///d+ (///./d+)?///////////////]) "; string operatorexp =" ((// d+(//.// d+)?) | (// [// [// -// d+(//.// d+)? //])) [//+//-] (// d+(//.// d+)?) | (//-// /d+ (////d+)?///]) ")"; if (expression.matches (not)) {pattern patt = pattern.compile (prioroperatexp); if (mat.find ()) {String Tempminexp = Mat.group (); Expression = Expression.ReplaceFirs (Prioroperatorexp, PARSEEXP (TEMPMINEXP));} Else { ompile (Operatorexp); Mat = Patt.matcher (Expression ); mat.find ()) {string tempminexp = mat.group (); expression = expression.replacefirst (Operatorexp, PARSEEXP (TEMPMINEXP)); XPression);} // Calculate four of parentheses Computing String MINPARENTHESES = "// ([^// (/)]+//)"; Pattern Patt = Pattern.compile (minparenthesees); matcher mat = patt.matcher (expression); if (mat.find () ) {String tempminexp = mat.group (); expression = expression.replacefirst (minparentheses, PARSEEXP (TEMPMINEXP)); /** * Calculate the minimum unit four operation formula (two numbers) * @param exp * @return */ public static String calculate(String exp){ exp=exp.replaceAll("[//[//]]", ""); String number[]=exp.replaceFirst("(/ /d) [//+//-//*///] "," $ 1, "). split (", "); BigDecimal Number1 = New Bigdecimal (Number [0]); number [1]); BigDecimal Result = NULL; String Operator = Exp.replacefirst ("^.*// D ([///////////bin $", "$ 1") ; if ("+". EQuals (Operator)) {result = number1.add (number2);} Else if ("-". EQUALS (Operator)) {Result = Number1.Subtract (Number2);} ELSE If " *". Equals (Operator)) {result = number1.multiply (number2);} Else if ("/". EQUALS (Operator)) {Result = Number1.divide (Number2); ULT! = Null? Result. Tostring (): null;}}
Finally, I will share with you the implementation method of a netizen.
Import java.util.stack; /*** uses the stack to perform four calculations classes* use two stacks to achieve the calculation preferred. One stack is used to save the data that needs to be calculated. * The implementation of the basic algorithm is: using the currently obtained operator with the PRISTACK stack top fans: If it is higher, it will be calculated first and put it in the top of the stack; Calculate, so the top element is out of the stack to remove the operating number of operations; * If it is less, the same is true. Take out the top element operation of the stack and put the result into the operating number stack. Each priority '('> ' *' = '/'> '+' = '-'> ')' * * */public class operate {Private Stack <cHaracter> Pristack = New Stack <); // The operating zoning stack Private Stack <Integer> Numstack = New Stack <Integer> (); // Operation number stack/*** Pass in the string that needs to be parsed, and return the calculation results (here is due to time problems, omitting legitimacy verification verification )* @Param Str needs to perform technical expression* @Return Calculation results*/ public into (String Str) {// 1. Determine whether there are illegal characters in String String Temp; // // 2. The loop starts to parse the string. When the string is parsed and the symbol stack is empty, the calculation is completed StringBuffer tempNum = new StringBuffer();// Used to temporarily store numeric strings (when it is multi-digit number ) StringBuffer string = new StringBuffer().append(str);// Used to save and improve efficiency while (string.length() != 0) { temp = string.substring(0, 1); string.delete(0 , 1); // Judge temp. When temp is the operator if (!isNum(temp))) { // 1. At this time, the number that needs to be operated is the number, take out the number, press the stack, and clear the tempNum if (! "" ". Equals (tempnum.tostring ())) {// When the first symbol of the expression is the bracket int Num = Integer.parseint (tempnum.tostring ()); delete (0, tempnum.length ());} // Use the currently obtained operator to be prioritized with the stacking calculation symbol: if it is higher, it will be calculated first, put on the top of the stack; Later, it will be calculated later, so the top elements of the stack are out of the stack and remove the operating number of operations; // If it is less, the same is true. Take out the top element operation of the stack and put the result into the operating number stack. // Determine the priority of the current computing symbol and the top element of the stack, take out the elements, and calculate (because the priority may be less than the top element of the stack, it is also less than the second element, etc., you need to use a cycle judgment). (0)) && (! Pristack.empty ()) {int a = (int) numstack.pop (); // The second operation number int b = (int) numstack.pop (); // First first CHAR OPE = Pristack.pop (); int result = 0; // The operation result switch (open) {// If it is plus or minus number, then case ' +': result = b + a; // Put the operation results in the operation number numstack.push (result); break; case ' -': result = b -a; // Put the operating results in the operating number stack numstack.push (result); bream; case '* ': result = b * a; // Put the operating results in the operating number of numstack.push (result); break; case'/ ': result = b/ a; // Put the operating result in the operating number of numstack. push (result); BREAK;}} // Judging the priority of the current operator and the top element of the stack. 0) != '#') { priStack.push(new Character(temp.charAt(0))); if (temp.charAt(0) == ')') {// When the top of the stack is '(', When the current element is ')', it is in the bracket to calculate, and remove the parentheses propack.pop (); Pristack.pop ();}}} else // When it is a non -operating symbol (digital) tempnum = tempnum. APPEND (Temp); // After receiving the number of digits read to the number of reads (when it is not a single digit)} Return numstack.pop (); Is it a 0-9 number * * * @Param Str * string transmitted * @Return * / Private Boolean isnum (String Temp) {Return Temp.matches ("[0-9]");} / ** * Compare the current operating symbols and the top element operating symbols of the stack. If it is higher than the top element of the stack, returns true, otherwise it is necessary to return False * * * @Param STR. High priority, FALSE represents lower priority than the top element of the stack*/ Private Boolean Compare (Char Str) {if (Pristack.empty ()) {// When it is empty, it is obviously the lowest priority. } char last = (char) propack.lastelement (); // If the top of the stack is '(' Obviously, the priority is the lowest, ')' cannot be the top of the stack. if (last == '(') {Return True;} Switch (Str) {case '#': Return false; // The ending character " ; case ')': // ')') 'The lowest priority, return false; case'*': {//'*/' == '-') Return true; Else Return false;} case '/': {if (last == '+' || Last == '-') Return true; 'For the minimum, always return to False Case'+': Return false; case'-': Return false;} Return True;} Public Static void Main (String ARGS []) {operate operate = n ew operate (); int T = operate.caculating ("(3+4*(4*10-10/2)#"); System.out.println (t);}}