A class written in Java to implement a large number Calculator

Source: Internet
Author: User

To practice Java programming, I wrote a class that can calculate large numbers. I only need to call a method of this class and use the arithmetic expression as a parameter to return the calculation result.

Import java. math. bigInteger; import java. util. emptyStackException; import java. util. hashMap; import java. util. stack;/** this class implements the function of simple calculation of the Worker Number **/class BigNumCalculator {private String input; // The expression to be calculated private String output; // The settlement result Stack
 
  
Operand; // operand Stack
  
   
Operator; // operator stack HashMap
   
    
Prect_map; // ing between operators and priorities/** no-argument constructor **/public BigNumCalculator () {this. operand = new Stack
    
     
(); This. operator = new Stack
     
      
(); Prect_map = new HashMap
      
        (); Prect_map.put ("+", new Integer (1); prect_map.put ("-", new Integer (1); prect_map.put ("*", new Integer (2); prect_map.put ("/", new Integer (2);}/** perform a simple check on the input expression. Valid characters: Numbers, +,-, *,/, (,), and other characters. * return value: true if the expression does not contain invalid characters, otherwise, false * is returned to call this function: No **/private void check () throws ExpressionException {if (! This. input. matches ("[\ d \ + \-\ */()] *") // use a regular expression to check whether the expression is legal. If the expression is invalid, throw an invalid expression. If you do not understand the regular expression, refer to the following link: open throw new ExpressionException ("Expressions contain only numbers, + ,-,*,/");} /** function: Compare the priority of two operators * parameter: the two operators to be compared * return value: If 1. The first operator has a lower priority than the second operator, a negative value is returned; * 2. Return 0 if the priority is the same. * 3. The first operator is higher than the second operator. Return a positive value * call this function: No **/private int compOperator (String op1, string op2) {return this. prect_map.get (op1 ). intValue ()-this. prect_map. Get (op2 ). intValue ();}/** function: Calculate two specified large number Objects Based on the specified operator to obtain the result * parameter: the two large number objects to be calculated, returns a large integer Class Object, indicating the operation result * calls this class function: None **/private BigInteger compute (BigInteger bi1, BigInteger bi2, string operator) {switch (operator. charAt (0) {case '+': return bi1.add (bi2); case '-': return bi1.subtract (bi2); case '*': return bi1.multiply (bi2 ); case '/': return bi1.divide (bi2); default: return null;}/** function: The input expression calculates the result represented by a String * parameter: A String object, indicating the expression to be calculated * return value: A String object, indicating the result of settlement * exception thrown: if the expression is invalid, an exception is thrown * Calling functions in this class: check (), compOperator (), compute () **/public String calculate (String input) throws ExpressionException {input = "(" + input + ")"; // assign the passed expression string to the class member, and enclose the expression with parentheses, this. input = input; this. check (); // check whether the expression is legal StringBuffer sb = new StringBuffer (); // It is used to store numbers for (int j = 0; j <p Ut. length (); j ++) {String tmp = "" + input. charAt (j); // converts the character currently being parsed to the string if (tmp. matches ("\ d") {// The number sb is currently parsed. append (tmp. charAt (0);} else if (tmp. charAt (0) = '(') {// currently parsed is '(' // (the first part must be next to the operator, so we do not need to stack the operands, this is because the StringBuffer object must be empty. operator. push (tmp);} else if (tmp. matches ("[\ + \-\ */] {1}") {// currently parsed operators include +,-, *, and, convert the previous string into a large number, push it into the operand stack, and clear the StringBuffer object storing the number BigInteger biTemp = new BigInteger (sb. toStrin G (); this. operand. push (biTemp); sb. delete (0, sb. length ();/* The operator whose priority is lower than or equal to the current operator in the execution operator stack * First, an operator is popped up from the operator stack, * two operands * are displayed from the operand stack. After the operation is executed, the result is pushed to the operand stack. **/while (! This. operator. empty () {String topOperator = this. operator. pop (); if (topOperator. equals ("(") {// if you encounter "(", stop processing this. operator. push (topOperator); break;} if (this. compOperator (tmp, topOperator) <= 0) {// If the operator priority in the stack is higher than the operator priority currently resolved or equal to BigInteger bi1 = this. operand. pop (); BigInteger bi2 = this. operand. pop (); this. operand. push (this. compute (bi1, bi2, topOperator);} else {// If the operator in the stack has a lower priority than the operator currently parsed this. operator. push (top Operator); // re-Press the pop-up Operator into the break of the Operator stack;} this. operator. push (tmp); // press the current operator into the operator stack} else {// if the right brackets are currently parsed) // convert the previous string into a large number, press it into the operand stack, and clear the StringBuffer object storing numbers BigInteger biTemp = new BigInteger (sb. toString (); this. operand. push (biTemp); sb. delete (0, sb. length (); try {String topOperator = this. operator. pop (); while (! TopOperator. equals ("(") {BigInteger bi1 = this. operand. pop (); BigInteger bi2 = this. operand. pop (); this. operand. push (this. compute (bi1, bi2, topOperator); topOperator = this. operator. pop () ;}} catch (EmptyStackException e) {throw new ExpressionException () ;}} if (! This. operator. empty () | this. operand. size ()! = 1) throw new ExpressionException (); this. output = this. operand. pop (). toString (); return this. output ;}}
      
     
    
   
  
 

The above class references a self-compiled exception class:

/** An exception class compiled by yourself. If the expression is invalid, this Exception is thrown **/class ExpressionException extends Exception {/***/private static final long serialVersionUID = 1L; public ExpressionException (String msg) {super (msg );} public ExpressionException () {super ("parsing fault ");}}


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.