Java for arithmetic

Source: Internet
Author: User

The basic principle of arithmetic is to convert infix expressions into suffix expressions. And then the calculation.

Conversion ideas and principles, you can refer to the infix expression into a suffix expression


Import Java.math.bigdecimal;import java.util.arraylist;import Java.util.list;import Java.util.stack;import Java.util.regex.pattern;public class Arithmetic {//operator stackprivate stack<string> operator = new stack<string > ();//suffix expression private list<string> PostFix = new arraylist<string> ();p rivate Pattern Operatorpattern = Pattern.compile ("[\\d\\.]"); Private Pattern Arithmeticpattern = Pattern.compile ("[\ \ \ \ \\+\\-\\*\\/]");//convert infix expression to suffix expression public void parse (String s {s = replace (s); int j = 0;for (int i = 0; i < s.length (); i++) {String temp = s.substring (i, i + 1); if (Operatorpatte Rn.matcher (temp). Matches ()) {continue;} if (Arithmeticpattern.matcher (temp). Matches ()) {j = Process (J, I, S, temp);} else if ("". Equals (temp)) {return;}} if (J < s.length ()) {Postfix.add (S.substring (J, S.length ()));} while (!this.operator.isempty ()) {Postfix.add (Operator.pop ());}} private string Replace (string s) {return S.replaceall ("\\s", "");} private int process (int startIndex, int currenTindex, String str, string word) {if (StartIndex! = currentindex) {postfix.add (str.substring (StartIndex, Currentindex));} Addoperator (word); StartIndex = Currentindex + 1;if (StartIndex > Str.length ()) {StartIndex = Str.length ();} return startIndex;} public void Addoperator (String operator) {if ("(". Equals (operator)) {} else if (")". Equals (operator)) {while (! This.operator.isEmpty ()) {String temp = This.operator.pop (); if (". Equals (temp)) {break;} else {postfix.add (temp);}} return;} else if (!this.operator.isempty ()) {while (!this.operator.isempty ()) {String temp = This.operator.peek (); if (Needpop ( Temp, operator)) {This.postFix.add (This.operator.pop ());} else {break;}}} This.operator.add (operator);} public boolean Needpop (string instacktop, string current) {return Getlevel (Current.charat (0)) <= getlevel ( Instacktop.charat (0));} public int Getlevel (char operator) {switch (operator) {case ' + ': return 1;case '-': return 1;case ' * ': return 2;case '/': Retu RN 2;default:return-1;}} Public BigDecimal Compute () {stack<bigdecimal> Stack = new stack<bigdecimal> (); for (int i=0; i < this.postFix.size (); i++) {if (Arithmeticpattern.matcher (Postfix.get (i)). Matches ()) {BigDecimal Bd2 = Stack.pop (); BigDecimal bd1 = Stack.pop (); BigDecimal temp = COMPUTE (Postfix.get (i). CharAt (0), BD1, Bd2); Stack.add (temp);} else {stack.add (new BigDecimal (Postfix.get (i)));}} return Stack.pop ();} Private BigDecimal Compute (char operator, BigDecimal BD1, BigDecimal bd2) {switch (operator) {case ' + ': Return Bd1.add (BD2) Case '-': Return Bd1.subtract (BD2), Case ' * ': return bd1.multiply (BD2), Case '/': Return Bd1.divide (BD2);// Should use Bd1.divide (divisor, scale, roundingmode);d Efault:return null;}} public static void Main (string[] args) {Arithmetic arithmetic = new arithmetic (); Arithmetic.parse ("+ + (3-1) *3+10/2"); System.out.println (Arithmetic.postfix); System.out.println (Arithmetic.compute ()); arithmetic = new Arithmetic (); Arithmetic.parse ("+ + (3-1) *3+10/2+1000-200- (100+5-9/3) "); System.out.println (Arithmetic.postfix);  System.out.println (Arithmetic.compute ()); arithmetic = new Arithmetic (); Arithmetic.parse ("9 + (3-1) * 3 + 10/2 + 1000- 200-(100 + 5-9/3) "); System.out.println (Arithmetic.postfix); System.out.println (Arithmetic.compute ());}}


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.