Android Simple Calculator

Source: Internet
Author: User

Algorithm used: expression evaluation (infix expression to suffix expression, suffix expression evaluation value)

Not how to design the interface, there is time to beautify!

Mainactivity.java

Package Com.example.calculator;import Java.util.hashmap;import Java.util.linkedlist;import java.util.List;import Java.util.map;import Android.app.activity;import Android.os.bundle;import Android.view.menu;import Android.view.view;import Android.widget.button;import Android.widget.textview;import Android.widget.Toast;public Class Mainactivity extends Activity {String mid=null; TextView textview=null;//operation Fu Yi static linkedlist<string> opstack=new linkedlist<string> ();//Priority mapping static Map<string, integer> priority=new hashmap<string, integer> () {Put ("(", 0);p ut (")", 0);p ut ("+", 1);p ut ("-" , 1);p ut ("x", 2);p ut ("÷", 2);}}; public void init () {textview= (TextView) Findviewbyid (R.id.textview); textview.settextsize (30);} @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.layout.activity_main); init ();} @Overridepublic boolean Oncreateoptionsmenu (Menu menu) {getmenuinflater (). Inflate (R.menu.main, menu); return true;} Public VoiD Delete (view view) {String text = (string) textview.gettext (); if (Text!=null&&text.length ()!=0) {text= Text.substring (0, Text.length ()-1); Textview.settext (text);}} public void Clear (view view) {Textview.settext ("");} public void Showtext (view view) {button bt= (button) view; string s = (string) bt.gettext ();//toast.maketext (this, S, Toast.length_long). Show (); String text = (string) textview.gettext (); Textview.settext (text+s);} public void Calc (view view) {mid = (String) textview.gettext (); String[] Midsplit=gotosplit (mid);D ouble ans=0.; Try {list<string> after = Midtoafter (Midsplit), ans = aftervalue (after); Textview.settext (ans.tostring ());} catch (Exception e) {Toast.maketext (this, "input not valid, please check", Toast.length_long). Show ();}} Public string[] Gotosplit (String s) {int pre=-1;//The position of the previous symbol, when two symbols together:) * should be divided into: *# otherwise divided into: #* #StringBuffer sb=new StringBuffer ( ); for (int i=0;i<s.length (); i++) {if (S.charat (i)! = '. ') && (S.charat (i) < ' 0 ' | | S.charat (i) > ' 9 ') {if (I-1==pre) {//previous is also the action symbol Sb.append (S.charat(i) + "#");} else Sb.append ("#" +s.charat (i) + "#");p re=i;//update pre}else{sb.append (S.charat (i));}} string[] split = Sb.tostring (). Split ("#"); return split;} /** * infix suffix: * Left-to-right scan expression * A: If the digital direct output * B: if (directly into the stack * C: IF) the stack of operators back to the stack output, until the encounter (so far, the stack is discarded * d other: The priority of the current operator is less than equal to the top of the stack operator priority, then the stack top operation Output. Until it is not less than or empty; */public the current operator into the stack static list<string> midtoafter (String [] mid) throws Exception{linkedlist<string > After=new linkedlist<string> (); int index=0;for (String ss:mid) {if (ss.equals ("=")) continue;if ( Priority.get (ss) ==null) {//description is operand after.add (ss);} else if (ss.equals (")") {Opstack.push (ss);} else if (ss.equals (")")) {while (!opstack.peek (). Equals ("(")) {///not "(", then output, After.add (Opstack.pop ());} Opstack.pop ();//Remove (}else {while (!opstack.isempty () &&priority.get (ss) <=priority.get (Opstack.peek ())) { After.add (Opstack.pop ());} Opstack.push (ss);}} while (!opstack.isempty ()) After.add (Opstack.pop ()), return after;} /** * Suffix evaluation: Left-to-right scan suffix expression * A: if it is a number, directly into the stack * B: If it is an operator, stack two numbers from the stack, calculate by operator, then put the results into the stack, note the two operand order * results: The last stack has only one number,The stack is the answer * @param after * @return */public static double Aftervalue (list<string> after) throws Exception{linkedlist&lt ;D ouble> number=new linkedlist<double> (); for (String Ss:after) {if (Priority.get (ss)!=null) {//is an operator, remove two numbers. Calculates the post-enter number stack by operator Double Y=number.pop ();D ouble x=number.pop (), if (Ss.equals ("+")) Number.push (x+y), Else if (ss.equals ("-")) Number.push (x-y), else if (Ss.equals ("x")) Number.push (x*y), Else if (ss.equals ("÷")) Number.push (x/y);} Else{number.push (double.valueof (ss));}} return Number.pop ();}}


Activity_main.xml

<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= "http// Schemas.android.com/tools "android:layout_width=" match_parent "android:layout_height=" Match_parent "Android:paddi ngbottom= "@dimen/activity_vertical_margin" android:paddingleft= "@dimen/activity_horizontal_margin" Android: paddingright= "@dimen/activity_horizontal_margin" android:paddingtop= "@dimen/activity_vertical_margin" tools: Context= ". Mainactivity "android:orientation=" vertical "> <textview android:id=" @+id/textview "android:l Ayout_width= "Match_parent" android:layout_height= "100DP" android:hint= "0"/> <tablel Ayout android:layout_width= "match_parent" android:layout_height= "match_parent" > <tabler            ow android:layout_width= "match_parent" android:layout_height= "Match_parent" > <button android:layout_width= "60DP"                android:layout_height= "60DP" android:text= "(" android:onclick= "Showtext" /> <button android:layout_width= "60DP" Android                                : layout_height= "60DP" android:text= ")" android:onclick= "Showtext"                /> <button android:layout_width= "60DP" android:layout_height= "60DP" android:text= "C" android:onclick= "clear"/> < Button android:layout_width= "60DP" android:layout_height= "60DP" Android:text = "DEL" android:onclick= "delete"/> </TableRow> <t            Ablerow android:layout_width= "match_parent" android:layout_height= "Match_parent" >         <button        Android:layout_width= "60DP" android:layout_height= "60DP" android:text= "7" android:onclick= "Showtext"/> <button android:layout_ Width= "60DP" android:layout_height= "60DP" android:text= "8" android:onclick= "s                Howtext "/> <button android:layout_width=" 60DP "                                android:layout_height= "60DP" android:text= "9" android:onclick= "Showtext" /> <button android:layout_width= "60DP" Android:layout_hei         ght= "60DP" android:text= "÷" android:onclick= "Showtext"/> </TableRow> <tablerow android:layout_width= "Match_parent" android:layout_height         = "Match_parent"   > <button android:layout_width= "60dp" android:layout_height= "60DP" android:text= "4" android:onclick= "Showtext"/> < Button android:layout_width= "60DP" android:layout_height= "60DP" Android:text                 = "5" android:onclick= "Showtext"/> <button Android:layout_width= "60DP" android:layout_height= "60DP" android:text= "6" and roid:onclick= "Showtext"/> <button android:layout_width= "6                                 0DP "android:layout_height=" 60DP "android:text=" x "android:onclick=" Showtext " /> </TableRow> <tablerow android:layout_width= "MATC H_parent "Android: layout_height= "Match_parent" > <button android:layout_width= "60DP"                                android:layout_height= "60DP" android:text= "1" android:onclick= "Showtext" /> <button android:layout_width= "60DP" Android:layout_hei            ght= "60DP" android:text= "2" android:onclick= "Showtext"/>                <button android:layout_width= "60DP" android:layout_height= "60DP"                 android:text= "3" android:onclick= "Showtext"/> <button                Android:layout_width= "60DP" android:layout_height= "60DP" android:text= "-"             android:onclick= "Showtext"/> </TableRow> <tablerow Android:layoUt_width= "Match_parent" android:layout_height= "match_parent" > <button                Android:layout_width= "60DP" android:layout_height= "60DP" android:text= "." android:onclick= "Showtext"/> <button android:layout_width = "60DP" android:layout_height= "60DP" android:text= "0" android:onclick= "Showte                XT "/> <button android:layout_width=" 60DP "                                android:layout_height= "60DP" android:text= "=" android:onclick= "Calc" /> <button android:layout_width= "60DP" android:layout_height= "60DP "android:text=" + "android:onclick=" Showtext "/> & Lt;/tablerow> </taBlelayout></linearlayout> 





Copyright notice: This article blog original articles, blogs, without consent, may not be reproduced.

Android Simple Calculator

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.