安卓实战:简易计算器
项目介绍
练手项目。能实现加减乘除及括号运算。
开发思路
界面布局
1.界面布局分三大块:公式文本区、结果文本区、按钮区。
2.通过点击按钮录入数学公式,实时展示在公式文本区。
3.点击等号,计算结果展示在结果文本区。
4.另外还有清空数据和删除一个字符功能。
计算逻辑
1.将中缀表达式转换为后缀表达式
2.计算后缀表达式得出结果
其他说明
栈数据结构简单说明:
1.栈数据结构像弹夹一样,先压进去的子弹后打出来,后压进去的子弹先打出来
2.入栈:将元素放进栈里,并改变栈顶指针
3.出栈:将元素从栈里拿出来,并改变栈顶指针
4.查看栈顶,取得栈顶元素,但不改变栈顶指针
中缀表达式转后缀表达式简单说明
1.如果是数字,直接放进后缀表达式里。
2.如果是左括号,入栈。
3.如果是右括号,依次出栈(放到后缀表达式里),直到遇到左括号。
4.运算符号:
1.空栈或栈顶是左括号,入栈
2.栈顶符号优先级比当前符号小,入栈
3.栈顶符号优先级大于等于当前符号,依次出栈(放到后缀表达式里),直到遇到不满足条件的元素或栈被掏空。
5.最后如果栈还有符号,依次出栈(放到后缀表达式里)
后缀表达式计算简单说明
1.如果是数字,入栈
2.如果是运算符,将栈顶的两个数字弹出并计算(先出栈的数字放在运算符后面进行计算),再将计算结果入栈。
代码
界面代码
<?xml version="1.0" encoding="utf-8"?>
<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:orientation="vertical"
tools:context=".MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
<TextView
android:id="@+id/the_expression"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="right"
android:textSize="50dp" />
</LinearLayout>
<View
android:layout_width="wrap_content"
android:layout_height="2dp"
android:background="#000" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
<TextView
android:id="@+id/the_result"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="right"
android:textSize="50dp" />
</LinearLayout>
<View
android:layout_width="wrap_content"
android:layout_height="2dp"
android:background="#000" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
<Button
android:id="@+id/left_bracket"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="("
android:textSize="30sp" />
<Button
android:id="@+id/right_bracket"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:text=")"
android:textSize="30sp" />
<Button
android:id="@+id/clear"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="C"
android:textSize="30sp" />
<Button
android:id="@+id/delete"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="DEL"
android:textSize="30sp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
<Button
android:id="@+id/seven"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="7"
android:textSize="30sp" />
<Button