要求:
- 完成一個計算器的設計,可以以手機自帶的計算器為參考。設計過程中,注意考慮界面的美觀性,不同機型的適應性,以及功能的完備性。
- 注意結合Activity的生命周期,考慮不同情況下計算器的界面狀態。
一.java目錄下的代碼:
1.MainActivity.java
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private static String TAG="LIFECYCLE";
Button btn_0;
Button btn_1;
Button btn_2;
Button btn_3;
Button btn_4;
Button btn_5;
Button btn_6;
Button btn_7;
Button btn_8;
Button btn_9;
Button btn_point; //小數點
Button btn_clear; //清除
Button btn_del; //刪除
Button btn_plus;
Button btn_minus;
Button btn_multiply;
Button btn_divide;
Button btn_equal;
Button btn_left;
Button btn_right;
private TextView et_input;
private StringBuilder pending = new StringBuilder();
private void initView() {
btn_0 = (Button) findViewById(R.id.btn_0);
btn_1 = (Button) findViewById(R.id.btn_1);
btn_2 = (Button) findViewById(R.id.btn_2);
btn_3 = (Button) findViewById(R.id.btn_3);
btn_4 = (Button) findViewById(R.id.btn_4);
btn_5 = (Button) findViewById(R.id.btn_5);
btn_6 = (Button) findViewById(R.id.btn_6);
btn_7 = (Button) findViewById(R.id.btn_7);
btn_8 = (Button) findViewById(R.id.btn_8);
btn_9 = (Button) findViewById(R.id.btn_9);
btn_point = (Button) findViewById(R.id.btn_point);
btn_clear = (Button) findViewById(R.id.btn_clear);
btn_del = (Button) findViewById(R.id.btn_del);
btn_plus = (Button) findViewById(R.id.btn_plus);
btn_minus = (Button) findViewById(R.id.btn_minus);
btn_multiply = (Button) findViewById(R.id.btn_multiply);
btn_divide = (Button) findViewById(R.id.btn_divide);
btn_equal = (Button) findViewById(R.id.btn_equal);
et_input = (TextView) findViewById(R.id.et_input);
btn_left = (Button) findViewById(R.id.btn_left);
btn_right = (Button) findViewById(R.id.btn_right);
btn_0.setOnClickListener(this);
btn_1.setOnClickListener(this);
btn_2.setOnClickListener(this);
btn_3.setOnClickListener(this);
btn_4.setOnClickListener(this);
btn_5.setOnClickListener(this);
btn_6.setOnClickListener(this);
btn_7.setOnClickListener(this);
btn_8.setOnClickListener(this);
btn_9.setOnClickListener(this);
btn_point.setOnClickListener(this);
btn_plus.setOnClickListener(this);
btn_equal.setOnClickListener(this);
btn_minus.setOnClickListener(this);
btn_multiply.setOnClickListener(this);
btn_del.setOnClickListener(this);
btn_divide.setOnClickListener(this);
btn_clear.setOnClickListener(this);
btn_divide.setOnClickListener(this);
btn_left.setOnClickListener(this);
btn_right.setOnClickListener(this);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
public void onClick(View v) {
int last = 0;
if(pending.length()!=0)
{
last = pending.codePointAt(pending.length()-1);
}
switch (v.getId()) {
case R.id.btn_0:
pending = pending.append("0");
et_input.setText(pending);
break;
case R.id.btn_1:
pending = pending.append("1");
et_input.setText(pending);
break;
case R.id.btn_2:
pending = pending.append("2");
et_input.setText(pending);
break;
case R.id.btn_3:
pending = pending.append("3");
et_input.setText(pending);
break;
case R.id.btn_4:
pending = pending.append("4");
et_input.setText(pending);
break;
case R.id.btn_5:
pending = pending.append("5");
et_input.setText(pending);
break;
case R.id.btn_6:
pending = pending.append("6");
et_input.setText(pending);
break;
case R.id.btn_7:
pending = pending.append("7");
et_input.setText(pending);
break;
case R.id.btn_8:
pending = pending.append("8");
et_input.setText(pending);
break;
case R.id.btn_9:
pending = pending.append("9");
et_input.setText(pending);
break;
case R.id.btn_plus:
//if (last >= '0' && last <= '9' ) {
pending = pending.append("+");
// }
et_input.setText(pending);
break;
case R.id.btn_minus:
//if (last >= '0' && last <= '9') {
pending = pending.append("-");
// }
et_input.setText(pending);
break;
case R.id.btn_multiply:
// if (last >= '0' && last <= '9' ) {
pending = pending.append("*");
// }
et_input.setText(pending);
break;
case R.id.btn_divide:
// if (last >= '0' && last <= '9' ) {
pending = pending.append("/");
// }
et_input.setText(pending);
break;
case R.id.btn_point:
if (judje1()) {
pending = pending.append(".");
et_input.setText(pending);
}
break;
case R.id.btn_right:// )右括號
if((last>='0' &&last<='9'||last==')')&&judje2()==1) {
pending = pending.append(")");
et_input.setText(pending);
}
break;
case R.id.btn_left:// (左括號
if((last!='(')||(last<='0' &&last>='9')){
pending = pending.append("(");
et_input.setText(pending);
}
break;
case R.id.btn_del: //刪除
if (pending.length() != 0) {
pending = pending.delete(pending.length() - 1, pending.length());
et_input.setText(pending);
}
break;
case R.id.btn_clear: //清空
pending = pending.delete(0, pending.length());
et_input.setText(pending);
break;
case R.id.btn_equal: // =等於
if ((pending.length() > 1)) {
InfixInToDuffix inf = new InfixInToDuffix();
String jieguo;
try {
String a = inf.toSuffix(pending);
jieguo = inf.dealEquation(a);
} catch (Exception ex) {
jieguo = "出錯";
}
et_input.setText(pending + "=" + jieguo);
pending = pending.delete(0, pending.length());
if (Character.isDigit(jieguo.charAt(0))) {
pending = pending.append(jieguo);
}
}
break;
default:
break;
}
}
private boolean judje1() {
String a = "+-*/.";
int[] b = new int[a.length()];
int max;
for (int i = 0; i < a.length(); i++) {
String c = "" + a.charAt(i);
b[i] = pending.lastIndexOf(c);
}
Arrays.sort(b);
if (b[a.length() - 1] == -1) {
max = 0;
} else {
max = b[a.length() - 1];
}
if (pending.indexOf(".", max) == -1) {
return true;
} else {
return false;
}
}
private int judje2(){
int a=0,b=0;
for(int i = 0 ; i < pending.length() ;i++){
if(pending.charAt(i)=='(' ) {
a++;
}
if(pending.charAt(i)==')' ) {
b++;
}
}
if(a == b)
return 0;
if(a > b)
return 1;
return 2;
}
public void onStart(){
super.onStart();
Log.i(TAG,"onStart");
}
public void onResume(){
super.onResume();
Log.i(TAG,"onResume");
}
public void onRestart(){
super.onRestart();
Log.i(TAG,"onRestart");
}
public void onPause(){
super.onPause();
Log.i(TAG,"onPause");
}
public void onStop(){
super.onStop();
Log.i(TAG,"onStop");
}
public void onDestroy(){
super.onDestroy();
Log.i(TAG,"onDestroy");
}
}
2.InfixInToDuffix.java
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.lang.*;
import java.util.ArrayList;
import java.util.*;
public class InfixInToDuffix {
//使用集合定義好符號的運算優先級別
private static final Map<Character,Integer>basic =new HashMap<Character, Integer>();
static {
basic.put('-',1);
basic.put('+', 1);
basic.put('*', 2);
basic.put('/', 2);
basic.put('(', 0);//在運算中 ()的優先級最高,但是此處因程序中需要 故設置為0
}
//將中綴表達式轉換為后綴表達式
public String toSuffix(StringBuilder infix){
List<String> queue = new ArrayList<String>(); //定義隊列 用於存儲 數字 以及最后的 后綴表達式
List<Character> stack = new ArrayList<Character>(); //定義棧 用於存儲 運算符 最后stack中會被 彈空
char[] charArr = infix.substring(0,infix.length()).trim().toCharArray(); //字符數組 用於拆分數字或符號
String standard = "*/+-()"; //判定標准 將表達式中會出現的運算符寫出來
char ch = '&'; //在循環中用來保存 字符數組的當前循環變量的 這里僅僅是初始化一個值 沒有意義
int len = 0; //用於記錄字符長度 【例如100*2,則記錄的len為3 到時候截取字符串的前三位就是數字】
for (int i = 0; i < charArr.length; i++) { //開始迭代
ch = charArr[i]; //保存當前迭代變量
if(Character.isDigit(ch)) { //如果當前變量為 數字
len++;
}else if(ch == '.'){ //如果當前變量為 . 會出現在小數里面
len++;
}else if(standard.indexOf(ch) != -1) { //如果是上面標准中的 任意一個符號
if(len > 0) { //長度也有
queue.add(String.valueOf(Arrays.copyOfRange(charArr, i - len, i))); //說明符號之前的可以截取下來做數字
len = 0; //長度置空
}
if(ch == '(') { //如果是左括號
stack.add(ch); //將左括號 放入棧中
continue; //跳出本次循環 繼續找下一個位置
}
if (!stack.isEmpty()) { //如果棧不為empty
int size = stack.size() - 1; //獲取棧的大小-1 即代表棧最后一個元素的下標
boolean flag = false; //設置標志位
while (size >= 0 && ch == ')' && stack.get(size) != '(') { //若當前ch為右括號,則 棧里元素從棧頂一直彈出,直到彈出到 左括號
queue.add(String.valueOf(stack.remove(size))); //注意此處條件:ch並未入棧,所以並未插入隊列中;同樣直到找到左括號的時候,循環結束了,所以左括號也不會放入隊列中【也就是:后綴表達式中不會出現括號】
size--; //size-- 保證下標永遠在棧最后一個元素【棧中概念:指針永遠指在棧頂元素】
flag = true; //設置標志位為true 表明一直在取()中的元素
}
if(ch==')'&&stack.get(size) == '('){
flag = true;
}
while (size >= 0 && !flag && basic.get(stack.get(size)) >= basic.get(ch)) { //若取得不是()內的元素,並且當前棧頂元素的優先級>=對比元素 那就出棧插入隊列
queue.add(String.valueOf(stack.remove(size))); //同樣 此處也是remove()方法,既能得到要獲取的元素,也能將棧中元素移除掉
size--;
}
}
if(ch != ')') { //若當前元素不是右括號
stack.add(ch); //就要保證這個符號 入棧
} else { //否則就要出棧 棧內符號
stack.remove(stack.size() - 1);
}
}
if(i == charArr.length - 1) { //如果已經走到了 中綴表達式的最后一位
if(len > 0) { //如果len>0 就截取數字
queue.add(String.valueOf(Arrays.copyOfRange(charArr, i - len+1, i+1)));
}
int size = stack.size() - 1; //size表示棧內最后一個元素下標
while (size >= 0) { //一直將棧內 符號全部出棧 並且加入隊列中 【最終的后綴表達式是存放在隊列中的,而棧內最后會被彈空】
queue.add(String.valueOf(stack.remove(size)));
size--;
}
}
}
String a = queue.toString();
return a.substring(1,a.length()-1);
}
public String dealEquation(String equation){
String [] arr = equation.split(", "); //根據, 拆分字符串
List<String> list = new ArrayList<String>(); //用於計算時 存儲運算過程的集合【例如list中當前放置 100 20 5 / 則取出20/5 最終將結果4存入list 此時list中結果為 100 4 】
for (int i = 0; i < arr.length; i++) { //此處就是上面說的運算過程, 因為list.remove的緣故,所以取出最后一個數個最后兩個數 都是size-2
int size = list.size();
switch (arr[i]) {
case "+": double a = Double.parseDouble(list.remove(size-2))+ Double.parseDouble(list.remove(size-2)); list.add(String.valueOf(a)); break;
case "-": double b = Double.parseDouble(list.remove(size-2))- Double.parseDouble(list.remove(size-2)); list.add(String.valueOf(b)); break;
case "*": double c = Double.parseDouble(list.remove(size-2))* Double.parseDouble(list.remove(size-2)); list.add(String.valueOf(c)); break;
case "/": double d = Double.parseDouble(list.remove(size-2))/ Double.parseDouble(list.remove(size-2)); list.add(String.valueOf(d)); break;
default: list.add(arr[i]); break; //如果是數字 直接放進list中
}
}
return list.size()
== 1 ? list.get(0) : "運算失敗" ; //最終list中僅有一個結果,否則就是算錯了
}
}
二.res目錄下的布局activity_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="match_parent"
android:layout_height="match_parent"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:orientation="horizontal"
android:layout_weight="2"
>
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/et_input"
android:textSize="40sp"
/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:orientation="horizontal"
android:weightSum="4"
>
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:text="C"
android:textSize="40sp"
android:id="@+id/btn_clear"
android:layout_weight="1"
android:background="#ffffff"/>
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:text="/"
android:textSize="40sp"
android:id="@+id/btn_divide"
android:layout_weight="1"
android:background="#ffffff"/>
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:text="X"
android:textSize="40sp"
android:id="@+id/btn_multiply"
android:layout_weight="1"
android:background="#ffffff"/>
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:text="T"
android:textSize="40sp"
android:id="@+id/btn_del"
android:layout_weight="1"
android:background="#ffffff"/>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:gravity="center"
android:weightSum="4"
>
<Button
android:id="@+id/btn_7"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="#cfc"
android:text="7"
android:textSize="30sp" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:text="8"
android:textSize="30sp"
android:id="@+id/btn_8"
android:layout_weight="1"
android:background="#cfc"/>
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:text="9"
android:textSize="30sp"
android:id="@+id/btn_9"
android:layout_weight="1"
android:background="#cfc"/>
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:text="-"
android:textSize="50sp"
android:id="@+id/btn_minus"
android:layout_weight="1"
android:background="#ffffff"/>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="0dp"
android:orientation="horizontal"
android:layout_weight="1"
android:weightSum="4"
>
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:text="4"
android:textSize="30sp"
android:id="@+id/btn_4"
android:layout_weight="1"
android:background="#cfc"/>
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:text="5"
android:textSize="30sp"
android:id="@+id/btn_5"
android:layout_weight="1"
android:background="#cfc"/>
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:text="6"
android:textSize="30sp"
android:id="@+id/btn_6"
android:layout_weight="1"
android:background="#cfc"/>
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:text="+"
android:textSize="40sp"
android:id="@+id/btn_plus"
android:layout_weight="1"
android:background="#ffffff"/>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="0dp"
android:orientation="horizontal"
android:layout_weight="1"
android:weightSum="4"
>
<Button
android:id="@+id/btn_1"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="#cfc"
android:text="1"
android:textSize="30sp" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:text="2"
android:textSize="30sp"
android:id="@+id/btn_2"
android:layout_weight="1"
android:background="#cfc"/>
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:text="3"
android:textSize="30sp"
android:id="@+id/btn_3"
android:layout_weight="1"
android:background="#cfc"/>
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:text="."
android:textSize="40sp"
android:id="@+id/btn_point"
android:layout_weight="1"
android:background="#FFFFFF"/>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="0dp"
android:orientation="horizontal"
android:layout_weight="1"
android:weightSum="4"
>
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:text="("
android:textSize="30sp"
android:id="@+id/btn_left"
android:layout_weight="1"
android:background="#cfc"/>
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:text="0"
android:textSize="30sp"
android:id="@+id/btn_0"
android:background="#cfc"
android:layout_weight="1" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:text=")"
android:textSize="30sp"
android:id="@+id/btn_right"
android:layout_weight="1"
android:background="#cfc"/>
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:text="="
android:textSize="30sp"
android:id="@+id/btn_equal"
android:background="#99CCFF"
android:layout_weight="1" />
</LinearLayout>
</LinearLayout>
最后的效果為: