[Android] simple calculator using Stack

Source: Internet
Author: User

 

Preface

It took some time to help a friend develop a calculator, which may be useful in the future.

 

StatementWelcome to repost, but please keep the original source of the article :) blog Park: http://www.cnblogs.com farmer UNCLE: http://over140.cnblogs.com

 

Body

Private TextView mNumberText;
/** Format data */
Private static final DecimalFormat mFormat = new DecimalFormat (
"###############.######");
/** Stack */
Private Stack <String> mMathStack = new Stack <String> ();

/** Operations into the stack */
Private void push (char obj ){
Final int size = mMathStack. size ();
// Clear
If ('c' = obj ){
MMathStack. clear ();
MNumberText. setText ("0 ");
Return;
}

// Operation symbol
If ('+' = obj | '-' = obj | '*' = obj | '/' = obj | '= obj) {
Switch (size ){
Case 0:
Break;
Case 2:
If ('= '! = Obj)
MMathStack. set (1, obj + ""); // enter two operators at the same time, and replace the operators
Break;
Case 1:
If ('= '! = Obj)
MMathStack. push (obj + "");
Break;
Case 3:
String preResult = mFormat. format (calc ());
MMathStack. push (preResult );
If ('= '! = Obj)
MMathStack. push (obj + "");
MNumberText. setText (preResult );
Break;
}
Return;
}

String str = "";
Int location = 0;
Switch (size ){
Case 0:
MMathStack. push ("");
Case 1:
Str = mMathStack. peek ();
Break;
Case 2:
MMathStack. push ("");
Case 3:
Location = 2;
Str = mMathStack. peek ();
Break;
}

Int len = str. length ();
If ('D' = obj ){
// Delete
If (len> 1)
Str = str. substring (0, len-1 );
Else if (len = 1)
Str = "0 ";
} Else if ('F' = obj ){
If ("0". equals (str) | len = 0 ){
Return;
} Else if (str. charAt (0) = '-'){
Str = str. replace ('-', ''). trim ();
} Else {
Str = '-' + str;
}
} Else {
If ('.' = obj ){
If (str. indexOf (".")> 0)
Return;
} Else if ('0' = obj ){
If (str. length () = 0 | str. equals ("0 "))
Return;
}
Str + = obj;
}
If ('.'! = Obj)
Str = mFormat. format (parseDouble (str ));
MMathStack. set (location, str );
MNumberText. setText (str );
}

Private double calc (){
Double result = 0.0D;
If (mMathStack. size () = 3 ){
Double right = parseDouble (mMathStack. pop ());
String metadata = mMathStack. pop ();
Double left = parseDouble (mMathStack. pop ());
If ("+". equals (equals )){
Result = left + right;
} Else if ("-". equals (equals )){
Result = left-right;
} Else if ("*". equals (equals )){
Result = left * right;
} Else if ("/". equals (equals )){
If (right! = 0.0D)
Result = left/right;
}
}
Return result;
}

/** Parse text data */
Private double parseDouble (String str ){
Try {
Return Double. parseDouble (str );
} Catch (NumberFormatException e ){
Return 0.0D;
}
}

/** Click Event */
@ Override
Public void onClick (View v ){
Switch (v. getId ()){
Case R. id. btnDivi: // Division
Push ('/');
Break;
Case R. id. btnMult: // multiply
Push ('*');
Break;
Case R. id. btnMinus: // minus
Push ('-');
Break;
Case R. id. btnPlus: // Add
Push ('+ ');
Break;
Case R. id. btnClear: // C
Push ('C ');
Break;
Case R. id. btn0:
Push ('0 ');
Break;
Case R. id. btn1:
Push ('1 ');
Break;
Case R. id. btn2:
Push ('2 ');
Break;
Case R. id. btn3:
Push ('3 ');
Break;
Case R. id. btn4:
Push ('4 ');
Break;
Case R. id. btn5:
Push ('5 ');
Break;
Case R. id. btn6:
Push ('6 ');
Break;
Case R. id. btn7:
Push ('7 ');
Break;
Case R. id. btn8:
Push ('8 ');
Break;
Case R. id. btn9:
Push ('9 ');
Break;
Case R. id. btnDot:
Push ('.');
Break;
Case R. id. btnEqual: // =
Push ('= ');
Break;
Case R. id. btnPM: // symbol, positive and negative
Push ('F ');
Break;
Case R. id. btnDel: // <-delete
Push ('D ');
Break;
}
}

 

Code Description:

A). R. IDs are all buttons on the interface, which respectively represent addition, subtraction, multiplication, division, and 0-9.

B) basic principle: using the stack model, an operand + an operator + an operand completes an operation, clears the stack, and pushes the result to the bottom of the stack.

C). The maximum number of digits before the decimal point is 15 and the last six digits are supported. You can adjust the number to avoid overflow.

D) The UI and code will not be downloaded. You can encapsulate the required code into a tool class.

 

End

The stack model is also well-extended and supports other operators. It is very convenient to implement simple operations. If you have tested it briefly, there is no problem. please correct me if you have any questions :)

 

 

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.