Android簡易計算器

CalculateActivity.java:

   

package sugite.love;

import java.util.ArrayList;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class CalculateActivity extends Activity implements OnClickListener {
	/** Called when the activity is first created. */
	private EditText output;
	private EditText input;
	private Button btn0;
	private Button btn1;
	private Button btn2;
	private Button btn3;
	private Button btn4;
	private Button btn5;
	private Button btn6;
	private Button btn7;
	private Button btn8;
	private Button btn9;
	private Button btnadd;
	private Button btnsub;
	private Button btnmult;
	private Button btndev;
	private Button btnclear;
	private Button btnreset;
	private Button btnleft;
	private Button btnright;
	private Button btnresult;
	char ops[] = { '+', '-', '*', '/', '(', ')', '#' };/* 運算符數組 */
	int cmp[][] = { { 2, 2, 1, 1, 1, 2, 2 },/*
											 * 用來進行比較運算符優先級的矩陣,3代表'=',2代表
											 * '>',1代表'<',0代表不可比
											 */
	{ 2, 2, 1, 1, 1, 2, 2 }, { 2, 2, 2, 2, 1, 2, 2 }, { 2, 2, 2, 2, 1, 2, 2 },
			{ 1, 1, 1, 1, 1, 3, 0 }, { 2, 2, 2, 2, 0, 2, 2 },
			{ 1, 1, 1, 1, 1, 0, 3 } };
	StringBuffer str = new StringBuffer();//輸入的表達式
	boolean flag = true;//能否進行輸入的標誌

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		output = (EditText) findViewById(R.id.output);
		input = (EditText) findViewById(R.id.input);

		btn0 = (Button) findViewById(R.id.button_0);
		btn1 = (Button) findViewById(R.id.button_1);
		btn2 = (Button) findViewById(R.id.button_2);
		btn3 = (Button) findViewById(R.id.button_3);
		btn4 = (Button) findViewById(R.id.button_4);
		btn5 = (Button) findViewById(R.id.button_5);
		btn6 = (Button) findViewById(R.id.button_6);
		btn7 = (Button) findViewById(R.id.button_7);
		btn8 = (Button) findViewById(R.id.button_8);
		btn9 = (Button) findViewById(R.id.button_9);

		btnadd = (Button) findViewById(R.id.button_add);
		btnsub = (Button) findViewById(R.id.button_sub);
		btnmult = (Button) findViewById(R.id.button_mult);
		btndev = (Button) findViewById(R.id.button_dev);
		btnleft = (Button) findViewById(R.id.button_lc);
		btnright = (Button) findViewById(R.id.button_rc);

		btnclear = (Button) findViewById(R.id.button_clr);
		btnreset = (Button) findViewById(R.id.button_reset);
		btnresult = (Button) findViewById(R.id.button_is);

		btn0.setOnClickListener(this);
		btn1.setOnClickListener(this);
		btn2.setOnClickListener(this);
		btn3.setOnClickListener(this);
		btn4.setOnClickListener(this);
		btn5.setOnClickListener(this);
		btn6.setOnClickListener(this);
		btn7.setOnClickListener(this);
		btn8.setOnClickListener(this);
		btn9.setOnClickListener(this);
		btnleft.setOnClickListener(this);
		btnright.setOnClickListener(this);
		btnadd.setOnClickListener(this);
		btnsub.setOnClickListener(this);
		btnmult.setOnClickListener(this);
		btndev.setOnClickListener(this);
		btnclear.setOnClickListener(this);
		btnreset.setOnClickListener(this);
		btnresult.setOnClickListener(this);

	}

	@Override
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.button_0:
			SetInput('0');
			break;
		case R.id.button_1:
			SetInput('1');
			break;
		case R.id.button_2:
			SetInput('2');
			break;
		case R.id.button_3:
			SetInput('3');
			break;
		case R.id.button_4:
			SetInput('4');
			break;
		case R.id.button_5:
			SetInput('5');
			break;
		case R.id.button_6:
			SetInput('6');
			break;
		case R.id.button_7:
			SetInput('7');
			break;
		case R.id.button_8:
			SetInput('8');
			break;
		case R.id.button_9:
			SetInput('9');
			break;
		case R.id.button_add:
			SetInput('+');
			break;
		case R.id.button_sub:
			SetInput('-');
			break;
		case R.id.button_mult:
			SetInput('*');
			break;
		case R.id.button_dev:
			SetInput('/');
			break;
		case R.id.button_lc:
			SetInput('(');
			break;
		case R.id.button_rc:
			SetInput(')');
			break;
		case R.id.button_clr:
			Init();
			break;
		case R.id.button_reset://重置
			if (str.length() > 0 && flag) {
				str.deleteCharAt(str.length() - 1);
				input.setText(str);
				output.setText("");
			}
			break;
		case R.id.button_is://“=” 進行求值
			if (str.length() > 0) {
				str.append('#');
				ExpEvaluation();
			}
		}
	}

	public void SetInput(char ch) {
		if (flag) {
			str.append(ch);
			input.setText(str);
		}
	}

	private void ExpEvaluation() {//表達式求值的函數
		int i = 0, temp;
		char op;
		float a, b, v;
		ArrayList<Character> operator = new ArrayList<Character>(50);
		ArrayList<Float> operand = new ArrayList<Float>(50);
		operator.add(new Character('#'));
		char ch = str.charAt(i++);
		while (ch != '#'
				|| operator.get(operator.size() - 1).charValue() != '#') {
			if (!IsOperator(ch)) {//如果不是操作符
				temp = ch - '0';
				ch = str.charAt(i++);
				while (!IsOperator(ch)) {
					temp = temp * 10 + ch - '0';
					if (temp >= Integer.MAX_VALUE / 10) {
						output.setText("超出計算範圍,按C清零,重新輸入!");
						flag = false;
						return;
					}
					ch = str.charAt(i++);
				}
				operand.add(new Float((float) temp));
			} else {
				switch (Compare(operator.get(operator.size() - 1).charValue(),
						ch)) {
				case '<':
					operator.add(new Character(ch));
					ch = str.charAt(i++);
					break;
				case '=':
					op = operator.remove(operator.size() - 1).charValue();
					ch = str.charAt(i++);
					break;
				case '>':
					op = operator.remove(operator.size() - 1).charValue();
					if (operand.size() < 2) {
						output.setText("表達式錯誤,請按C清零,重新輸入!");
						flag = false;
						return;
					}
					b = operand.remove(operand.size() - 1).floatValue();
					a = operand.remove(operand.size() - 1).floatValue();
					v = Execute(a, op, b);
					operand.add(new Float(v));
					break;
				}
			}
		}
		v = operand.remove(operand.size() - 1).floatValue();
		output.setText(new Float(v).toString());
		str.delete(0, str.length());
		flag = false;
	}

	private void Init() {//初始化計算器
		input.setText("");
		output.setText("");
		str.delete(0, str.length());
		flag = true;
	}

	private float Execute(float a, char op, float b) {//二元表達式求值
		float result = 0.0f;
		switch (op) {
		case '+':
			result = a + b;
			break;
		case '-':
			result = a - b;
			break;
		case '*':
			result = a * b;
			break;
		case '/':
			result = a / b;
			break;
		}
		return result;
	}

	public boolean IsOperator(char c) {//判斷是否爲操作符
		for (int i = 0; i < 7; i++)
			if (c == ops[i])
				return true;
		return false;
	}

	public char Compare(char ch1, char ch2) { /* 比較運算符優先級函數 */
		int i, m = 0, n = 0;
		char pri = 0;
		int priority;
		for (i = 0; i < 7; i++) { /* 找到相比較的兩個運算符在比較矩陣裏的相對位置 */
			if (ch1 == ops[i])
				m = i;
			if (ch2 == ops[i])
				n = i;
		}
		priority = cmp[m][n];
		switch (priority) {
		case 1:
			pri = '<';
			break;
		case 2:
			pri = '>';
			break;
		case 3:
			pri = '=';
			break;
		case 0:
			System.out.println("表達式錯誤!\n");
			System.exit(0);
			break;
		}
		return pri;
	}
}

 

main.xml:

   

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#FEDAD7"
    >
	<TextView  android:layout_width="fill_parent"  android:layout_height="wrap_content" 
    	android:text="@string/hello"   android:textSize="20.0dip"/>
    <EditText android:layout_width="fill_parent" android:layout_height="wrap_content"
    	android:maxLines="2" android:id="@+id/input" android:editable="false"/>
    <EditText android:layout_width="fill_parent" android:layout_height="wrap_content"
    	android:maxLines="1" android:id="@+id/output" android:editable="false"
    	android:gravity="right"/>
    <TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent" android:layout_height="wrap_content">
    	<TableRow android:gravity="center">
    		<Button android:layout_width="60px" android:layout_height="wrap_content"
    				android:id="@+id/button_7" android:text="7" android:textSize="40.0dip"/>
    		<Button android:layout_width="60px" android:layout_height="wrap_content"
    				android:id="@+id/button_8" android:text="8" android:textSize="40.0dip"/>
    		<Button android:layout_width="60px" android:layout_height="wrap_content"
    				android:id="@+id/button_9" android:text="9" android:textSize="40.0dip"/>
    		<Button android:layout_width="60px" android:layout_height="wrap_content"
    				android:id="@+id/button_add" android:text="+" android:textSize="40.0dip"/>
    		<Button android:layout_width="60px" android:layout_height="wrap_content"
    				android:id="@+id/button_sub" android:text="-" android:textSize="40.0dip"/>
    	</TableRow>
    	<TableRow android:gravity="center">
    		<Button android:layout_width="60px" android:layout_height="wrap_content"
    				android:id="@+id/button_4" android:text="4" android:textSize="40.0dip"/>
    		<Button android:layout_width="60px" android:layout_height="wrap_content"
    				android:id="@+id/button_5" android:text="5" android:textSize="40.0dip"/>
    		<Button android:layout_width="60px" android:layout_height="wrap_content"
    				android:id="@+id/button_6" android:text="6" android:textSize="40.0dip"/>
    		<Button android:layout_width="60px" android:layout_height="wrap_content"
    				android:id="@+id/button_mult" android:text="×" android:textSize="40.0dip"/>
    		<Button android:layout_width="60px" android:layout_height="wrap_content"
    				android:id="@+id/button_dev" android:text="÷" android:textSize="40.0dip"/>
    	</TableRow>
    	<TableRow android:gravity="center">
    		<Button android:layout_width="60px" android:layout_height="wrap_content"
    				android:id="@+id/button_1" android:text="1" android:textSize="40.0dip"/>
    		<Button android:layout_width="60px" android:layout_height="wrap_content"
    				android:id="@+id/button_2" android:text="2" android:textSize="40.0dip"/>
    		<Button android:layout_width="60px" android:layout_height="wrap_content"
    				android:id="@+id/button_3" android:text="3" android:textSize="40.0dip"/>
    		<Button android:layout_width="60px" android:layout_height="wrap_content"
    				android:id="@+id/button_lc" android:text="(" android:textSize="40.0dip"/>
    		<Button android:layout_width="60px" android:layout_height="wrap_content"
    				android:id="@+id/button_rc" android:text=")" android:textSize="40.0dip"/>
    	</TableRow>
    	<TableRow android:gravity="center">
    		<Button android:layout_width="60px" android:layout_height="wrap_content"
    				android:id="@+id/button_0" android:text="0" android:textSize="40.0dip"/>
    		<Button android:layout_width="60px" android:layout_height="wrap_content"
    				android:id="@+id/button_clr" android:text="C" android:textSize="40.0dip"/>
    		<Button android:layout_width="60px" android:layout_height="wrap_content"
    				android:id="@+id/button_reset" android:text="R" android:textSize="40.0dip"/>
    		<Button android:layout_width="60px" android:layout_height="wrap_content"
    				android:id="@+id/button_is" android:text="=" android:textSize="40.0dip"/>
    		<Button android:layout_width="60px" android:layout_height="wrap_content"
    				android:id="@+id/button_point" android:text="." android:textSize="40.0dip"/>
    	</TableRow>
	</TableLayout>
</LinearLayout>



 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章