1.後綴表達式的計算規則:
後綴表達式的計算過程:從左到右掃描整個表達式,把每一個操做符應用到其以前兩個相鄰的操做數,並計算該結果,剩下的表達式以此類推。
1+23
能夠轉換成後綴表達式以下:
1 2 3 +
計算過程以下:
1 2*3 + --> 1 6 + -->7
程序設計的思路:java
/** * Created by Administrator on 2017/5/4 0004. */ import java.util.StringTokenizer; import java.util.Stack; public class MyDC { /** * constant for addition symbol */ private final char ADD = '+'; /** * constant for subtraction symbol */ private final char SUBTRACT = '-'; /** * constant for multiplication symbol */ private final char MULTIPLY = '*'; /** * constant for division symbol */ private final char DIVIDE = '/'; /** * the stack */ private Stack<Integer> stack; public MyDC() { stack = new Stack<Integer>(); } public int evaluate(String expr) { int op1, op2, result = 0; String token; StringTokenizer tokenizer = new StringTokenizer(expr); while (tokenizer.hasMoreTokens()) { token = tokenizer.nextToken(); //若是是運算符,調用isOperator if (isOperator(token)) { //從棧中彈出操做數2 op2 = (stack.pop()).intValue(); //從棧中彈出操做數1 op1 = (stack.pop()).intValue(); //根據運算符和兩個操做數調用evalSingleOp計算result; result = evalSingleOp(token.charAt(0), op1, op2); //計算result入棧; stack.push(new Integer(result)); } else { //若是是操做數 stack.push(new Integer(Integer.parseInt(token))); //操做數入棧; } } return result; } private boolean isOperator(String token) { return (token.equals("+") || token.equals("-") || token.equals("*") || token.equals("/")); } private int evalSingleOp(char operation, int op1, int op2) { int result = 0; switch (operation) { case ADD: result = op1 + op2; break; case SUBTRACT: result = op1 - op2; break; case MULTIPLY: result = op1 * op2; break; case DIVIDE: result = op1 / op2; } return result; } }
myDCTest代碼:linux
import junit.framework.TestCase; import java.util.Scanner; import junit.framework.TestCase; public class MyDCTester { public static void main (String[] args) { String expression, again; int result; try { Scanner in = new Scanner(System.in); do { MyDC evaluator = new MyDC(); System.out.println ("Enter a valid postfix expression: "); expression = in.nextLine(); result = evaluator.evaluate (expression); System.out.println(); System.out.println ("That expression equals " + result); System.out.print ("Evaluate another expression [Y/N]? "); again = in.nextLine(); System.out.println(); } while (again.equalsIgnoreCase("y")); } catch (Exception IOException) { System.out.println("Input exception reported"); } } }
簡易計算器代碼android
import java.awt.*; import java.awt.event.*; import java.util.Stack; public class Calculator implements ActionListener,MouseListener{ private Frame frame; private Panel panel; private Label memorFlag=new Label(); private double memor; private TextArea texpress; private boolean expressLegal=true;//檢測表達式是否合法 private Label lresult=new Label("0",Label.RIGHT); private Button btmemor[]=new Button[4];//0 MC, 1 MR, 2 M+ , 3 M- private Button []btarray=new Button[12]; private Button add=new Button("+"); private Button sub=new Button("-"); private Button mul=new Button("*"); private Button div=new Button("/"); private Button clean=new Button("C"); private Button backspace=new Button("←"); private Button leftbrack=new Button("("); private Button rightbrack=new Button(")"); private Font btFont=new Font("Roman",5,20); private Font tFont=new Font("Roman",1,16); public Calculator(){ int i=0; ////////////////////// 界 面 設 計 /////////////////////// frame=new Frame("計算器"); frame.setLayout(null); frame.setVisible(true); frame.setLocation(400, 200); frame.setSize(375, 470); frame.setResizable(false); frame.setBackground(new Color(217,228,241)); memorFlag.setSize(320, 30); memorFlag.setFont(tFont); memorFlag.setBackground(new Color(248,251,254)); memorFlag.setLocation(25, 42); texpress=new TextArea("0",3,20,TextArea.SCROLLBARS_NONE); texpress.setSize(320, 60); texpress.setBackground(new Color(248,251,254)); texpress.setFont(tFont); texpress.setLocation(25, 70); texpress.setCaretPosition(1); lresult.setSize(320, 30); lresult.setFont(tFont); lresult.setBackground(new Color(251,251,254)); lresult.setLocation(25, 131); panel=new Panel(); panel.setLayout(new GridLayout(6,4)); panel.setSize(320, 240); panel.setLocation(25, 185); panel.setBackground(new Color(217,228,241)); for(i=0;i<12;i++){ btarray[i]=new Button(String.valueOf(i)); btarray[i].setBackground(new Color(243,248,252)); btarray[i].setForeground(new Color(30,57,91)); //btarr[i].setSize(50,60); btarray[i].setFont(btFont); } btarray[10].setLabel("."); btarray[11].setLabel("="); for(i=0;i<4;i++){ btmemor[i]=new Button(); btmemor[i].setBackground(new Color(243,248,252)); btmemor[i].setForeground(new Color(30,57,91)); //btarr[i].setSize(50,60); btmemor[i].setFont(new Font("Roman",5,13)); panel.add(btmemor[i]); } btmemor[0].setLabel("MC"); btmemor[1].setLabel("MR"); btmemor[2].setLabel("M+"); btmemor[3].setLabel("M-"); leftbrack.setBackground(new Color(243,248,252)); leftbrack.setForeground(new Color(30,57,91)); leftbrack.setFont(btFont); rightbrack.setBackground(new Color(243,248,252)); rightbrack.setForeground(new Color(30,57,91)); rightbrack.setFont(btFont); clean.setBackground(new Color(243,248,252)); clean.setForeground(new Color(30,57,91)); clean.setFont(btFont); backspace.setBackground(new Color(243,248,252)); backspace.setForeground(new Color(30,57,91)); backspace.setFont(btFont); add.setBackground(new Color(243,248,252)); add.setForeground(new Color(30,57,91)); add.setFont(btFont); sub.setBackground(new Color(243,248,252)); sub.setForeground(new Color(30,57,91)); sub.setFont(btFont); mul.setBackground(new Color(243,248,252)); mul.setForeground(new Color(30,57,91)); mul.setFont(btFont); div.setBackground(new Color(243,248,252)); div.setForeground(new Color(30,57,91)); div.setFont(btFont); panel.add(backspace); panel.add(clean); panel.add(leftbrack); panel.add(rightbrack); panel.add(btarray[7]); panel.add(btarray[8]); panel.add(btarray[9]); panel.add(div); panel.add(btarray[4]); panel.add(btarray[5]); panel.add(btarray[6]); panel.add(mul); panel.add(btarray[1]); panel.add(btarray[2]); panel.add(btarray[3]); panel.add(sub); panel.add(btarray[0]); panel.add(btarray[10]); panel.add(btarray[11]); panel.add(add); frame.add(memorFlag); frame.add(lresult); frame.add(texpress); frame.add(panel); /////////////////////////爲組件添加事件/////////////////////// frame.addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent e){ System.exit(0); } }); //texpress. texpress.addKeyListener(new KeyAdapter(){ public void keyTyped(KeyEvent e){ String str=texpress.getText(); int pos=texpress.getCaretPosition(); int i=0; double resul=0; String behindExpress=null; char ch=e.getKeyChar(); if(ch==KeyEvent.VK_ENTER){//按鍵=或回車 i=str.indexOf("\n"); texpress.setText(str.substring(0, i-1)+str.substring(i+1, str.length())); texpress.setCaretPosition(pos); try{ behindExpress=toBehindExpress(); resul=getResult(behindExpress); }catch(Exception e2){ expressLegal=false; lresult.setText("ERROR"); }//catch if(expressLegal) lresult.setText(normalDouble(resul)); else expressLegal=true; }//if }//public }); for(i=0;i<4;i++){ btmemor[i].addActionListener(this); btmemor[i].addMouseListener(this); } for(i=0;i<12;i++){ btarray[i].addActionListener(this); btarray[i].addMouseListener(this); } backspace.addActionListener(this); backspace.addMouseListener(this); clean.addActionListener(this); clean.addMouseListener(this); leftbrack.addActionListener(this); leftbrack.addMouseListener(this); rightbrack.addActionListener(this); rightbrack.addMouseListener(this); add.addActionListener(this); add.addMouseListener(this); sub.addActionListener(this); sub.addMouseListener(this); mul.addActionListener(this); mul.addMouseListener(this); div.addActionListener(this); div.addMouseListener(this); } public String toBehindExpress(){//轉換爲後綴表達式 String behindExpress="",middleExpress=texpress.getText(),numStr=""; Stack s=new Stack(); int i=0; char ch,lb1=' ',lb2=' ',lm1=' ';//lb1表示behindExpress最後一個,lb2表示behindExpress倒數第二個 //lm1表示middleExpress中i的前一位置字符 while(i ch=middleExpress.charAt(i); if(behindExpress.length()>=1) lb1=behindExpress.charAt(behindExpress.length()-1); if(behindExpress.length()>=2) lb2=behindExpress.charAt(behindExpress.length()-2); if(i>0) lm1=middleExpress.charAt(i-1); switch(ch){ case '(': if(i!=0&&lm1!='('&&lm1!='+'&&lm1!='-'&&lm1!='*'&&lm1!='/'){ lresult.setText("ERROR"); //System.out.println(lm1!='*'); //System.out.println("??"+lm1); expressLegal=false; return ""; } s.push('('); i++; break; case ')': if(lb1!=' ') behindExpress+=' '; if(numStr.length()!=0){ behindExpress+=numStr; numStr=""; } while(!s.empty()&&s.peek()!='('){ if(behindExpress.charAt(behindExpress.length()-1)!=' ') behindExpress+=' '; behindExpress+=s.pop(); } s.pop();//右括號出棧 i++; break; case '0':case '1':case '2':case '3':case '4':case'5':case'6':case '7':case '8':case '9':case '.': if(lb1!=' ') behindExpress+=' '; numStr+=ch; i++; break; case '-'://須要考慮負號問題 if(i==0||lm1=='('||lm1=='+'||lm1=='-'||lm1=='*'||lm1=='/'){ numStr+=ch; i++; break; } case '+': case '*': case '/': if(lb1!=' ') behindExpress+=' '; if(numStr.length()!=0){ behindExpress+=numStr; numStr=""; } while(!s.empty()&&priorityLevel(s.peek())>=priorityLevel(ch)){ if(behindExpress.charAt(behindExpress.length()-1)!=' ') behindExpress+=' '; behindExpress+=s.pop(); } s.push(middleExpress.charAt(i)); i++; break; case ' ':i++;break; default :expressLegal=false;lresult.setText("ERROR");return ""; }//switch }//for if(numStr.length()!=0){ if(behindExpress.length()!=0&&behindExpress.charAt(behindExpress.length()-1)!=' ') behindExpress+=' '; behindExpress+=numStr; } while(!s.empty()){ if(behindExpress.charAt(behindExpress.length()-1)!=' ') behindExpress+=' '; behindExpress+=s.pop(); } behindExpress+=' '; //System.out.println(middleExpress); //System.out.println(behindExpress); //System.out.println(behindExpress+"後 "+i); return behindExpress; } public int priorityLevel(char ch){//'('優先級最低,')'優先級最高+、-一個優先級 *、/一個 switch(ch){ case '(': return 1; case '+': case '-': return 2; case '*': case '/': return 3; case ')': return 4; default : return -1; } } public double getResult(String express){//由後綴表達式計算結果 double num1,num2; int i=0; char ch; String temp=""; Stack s=new Stack(); if(expressLegal==false) return 0; for(i=0;i ch=express.charAt(i); if(ch>='0'&&ch<='9'||ch=='.'||(ch=='-'&&(i+1) temp+=ch; continue; } switch(ch){ case ' ': if(temp.length()!=0){ s.push(Double.parseDouble(temp)); temp=""; } break; case '+':case '-':case '*':case '/': num2=s.pop(); num1=s.pop(); if(ch=='+') s.push(num1+num2); if(ch=='-') s.push(num1-num2); if(ch=='*') s.push(num1*num2); if(ch=='/') { if(num2==0){ lresult.setText("除數不能爲零"); expressLegal=false; } s.push(num1/num2); } break; }//switch() }//for return s.pop(); } public String normalDouble(double num){ if((Math.round(num)-num)==0) return String.valueOf((long)num); return String.valueOf(num); } @Override public void actionPerformed(ActionEvent e) { int pos=texpress.getCaretPosition(); String str=texpress.getText(); Button e1=(Button)e.getSource(); if(str.equals("0")) str=""; if(e1==clean){ str=""; lresult.setText("0"); } else if(e1==backspace){ if(str.length()!=0&&pos!=0){ str=str.substring(0, pos-1)+str.substring(pos,str.length()); pos--; } } else if(e1==btmemor[0]){//清除memory memorFlag.setText(""); memor=0; } else if(e1==btmemor[1]){//提取memory str=normalDouble(memor); lresult.setText("0"); } else if(e1==btmemor[2]){//M+ try{ memor+=Double.parseDouble(lresult.getText()); }catch(Exception ex){} if(memor!=0) memorFlag.setText("M "+normalDouble(memor)); else memorFlag.setText(""); } else if(e1==btmemor[3]){//M- try{ memor-=Double.parseDouble(lresult.getText()); }catch(Exception ex){} if(memor!=0) memorFlag.setText("M "+normalDouble(memor)); else memorFlag.setText(""); } else if(e1==btarray[10]){//小數點 if(str.length()==0) str+="0."; else if(str.charAt(str.length()-1)!='.') str+="."; pos++; } else if(e1==btarray[11]){//等號 double resul=0; String behindExpress=null; try{ behindExpress=toBehindExpress(); resul=getResult(behindExpress); }catch(Exception e2){ expressLegal=false;lresult.setText("ERROR"); } if(expressLegal) lresult.setText(normalDouble(resul)); else expressLegal=true; } else{ if(str=="") str=e1.getLabel(); else if(str.length()==pos) str=str.substring(0,pos)+e1.getLabel(); else str=str.substring(0,pos)+e1.getLabel()+str.substring(pos,str.length()); pos++; } if(str.length()!=0) texpress.setText(str); else texpress.setText("0"); //texpress.setFocusable(true); texpress.requestFocus(); texpress.setCaretPosition(pos); } @Override public void mouseClicked(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mouseEntered(MouseEvent e) { // TODO Auto-generated method stub Button e1=(Button)e.getSource(); e1.setBackground(new Color(255,230,123)); } @Override public void mouseExited(MouseEvent e) { // TODO Auto-generated method stub Button e1=(Button)e.getSource(); e1.setBackground(new Color(243,248,252)); } @Override public void mousePressed(MouseEvent e) { // TODO Auto-generated method stub Button e1=(Button)e.getSource(); e1.setBackground(new Color(245,202,126)); } @Override public void mouseReleased(MouseEvent e) { // TODO Auto-generated method stub Button e1=(Button)e.getSource(); e1.setBackground(new Color(255,230,123)); } }
簡易計算器測試代碼git
package Test; public class CalculatorTest { public static void main(String[] args) { // TODO Auto-generated method stub Calculator ct= new Calculator(); } }
實驗結果
express
Android Stuidio的安裝測試: 參考《Java和Android開發學習指南(第二版)(EPUBIT,Java for Android 2nd)》第二十四章:android-studio
Activity測試: 參考《Java和Android開發學習指南(第二版)(EPUBIT,Java for Android 2nd)》第二十五章:app
UI測試: 參考《Java和Android開發學習指南(第二版)(EPUBIT,Java for Android 2nd)》第二十六章:ide
佈局測試: 參考《Java和Android開發學習指南(第二版)(EPUBIT,Java for Android 2nd)》第二十七章:函數
事件處理測試: 參考《Java和Android開發學習指南(第二版)(EPUBIT,Java for Android 2nd)》第二十八章:佈局
private View.OnClickListener MyListener = new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(MainActivity.this,"you have clicked Button2",Toast.LENGTH_SHORT).show(); } };
方法二:實現匿名內部類。這種方法適合只但願對監聽器進行一次性使用的狀況,在該代碼塊運行完畢以後,該監聽器也就不復存在了。
bt1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(MainActivity.this,"you have clicked Button1",Toast.LENGTH_SHORT).show(); } });
方法三:利用佈局文件中的onClick屬性,並在實現文件中實現該方法。注意的是這裏的方法名應該和佈局文件中onClick屬性的方法名相同,該方法必須是public方法。
public void onButtonClick (View view){ Toast.makeText(MainActivity.this,"you have clicked Button3",Toast.LENGTH_SHORT).show(); } }
佈局文件設置
<Button android:layout_below="@id/button2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/button3" android:text="Button3" android:onClick="onButtonClick"/>
完整代碼
佈局文件
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.example.jeffrey.listener.MainActivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/text" android:text="OnClickListener" /> <Button android:layout_below="@id/text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button1" android:id="@+id/button1"/> <Button android:layout_below="@id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button2" android:id="@+id/button2"/> <Button android:layout_below="@id/button2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/button3" android:text="Button3" android:onClick="onButtonClick"/> </RelativeLayout>
實現文件:
package com.example.jeffrey.listener; import android.content.DialogInterface; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.Toast; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button bt1 = (Button)findViewById(R.id.button1);//對應方法二 Button bt2 = (Button)findViewById(R.id.button2);//對應方法一 bt1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(MainActivity.this,"you have clicked Button1",Toast.LENGTH_SHORT).show(); } }); bt2.setOnClickListener(new MyListener()); } class MyListener implements View.OnClickListener{ @Override public void onClick(View v) { Toast.makeText(MainActivity.this,"you have clicked Button2",Toast.LENGTH_SHORT).show(); } } // 或者,這裏是建立一個OnClickListener 的對象,與上面的直接複寫接口有殊途同歸之妙 private View.OnClickListener MyListener = new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(MainActivity.this,"you have clicked Button2",Toast.LENGTH_SHORT).show(); } }; // 方法三,注意須要public方法 public void onButtonClick (View view){ Toast.makeText(MainActivity.this,"you have clicked Button3",Toast.LENGTH_SHORT).show(); } }