说明:
话不多说,先上图:
主要分为3部分:UI界面、逻辑代码、逻辑算法代码
UI界面:
上图中,采用LinearLayout布局,黄色外层使用 LinearLayout 的竖向布局,红色内层采用的是 LinearLayout 的横向布局,分为6块,使用的是权重比 weight,可以更好地调整横向的比例关系;
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:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:orientation="horizontal"
android:layout_weight="2">
<TextView
android:id="@+id/tv_input"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textSize="40sp"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:orientation="horizontal"
android:layout_weight="1"
android:weightSum="4">
<Button
android:id="@+id/bt_clear"
android:layout_width="0dp"
android:layout_height="match_parent"
android:text="C"
android:textSize="40sp"
android:layout_weight="1"
android:background="@drawable/button_selector"/>
<Button
android:id="@+id/bt_divide"
android:layout_width="0dp"
android:layout_height="match_parent"
android:text="/"
android:textSize="40sp"
android:layout_weight="1"
android:background="@drawable/button_selector"/>
<Button
android:id="@+id/bt_multiply"
android:layout_width="0dp"
android:layout_height="match_parent"
android:text="*"
android:textSize="40sp"
android:layout_weight="1"
android:background="@drawable/button_selector"/>
<Button
android:id="@+id/bt_del"
android:layout_width="0dp"
android:layout_height="match_parent"
android:text="T"
android:textSize="40sp"
android:layout_weight="1"
android:background="@drawable/button_selector"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:orientation="horizontal"
android:layout_weight="1"
android:weightSum="4">
<Button
android:id="@+id/bt_7"
android:layout_width="0dp"
android:layout_height="match_parent"
android:text="7"
android:textSize="30sp"
android:layout_weight="1"
android:background="@drawable/num_button_selector"/>
<Button
android:id="@+id/bt_8"
android:layout_width="0dp"
android:layout_height="match_parent"
android:text="8"
android:textSize="30sp"
android:layout_weight="1"
android:background="@drawable/num_button_selector"/>
<Button
android:id="@+id/bt_9"
android:layout_width="0dp"
android:layout_height="match_parent"
android:text="9"
android:textSize="30sp"
android:layout_weight="1"
android:background="@drawable/num_button_selector"/>
<Button
android:id="@+id/bt_minus"
android:layout_width="0dp"
android:layout_height="match_parent"
android:text="-"
android:textSize="50sp"
android:layout_weight="1"
android:background="@drawable/button_selector"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:orientation="horizontal"
android:layout_weight="1"
android:weightSum="4">
<Button
android:id="@+id/bt_4"
android:layout_width="0dp"
android:layout_height="match_parent"
android:text="4"
android:textSize="30sp"
android:layout_weight="1"
android:background="@drawable/num_button_selector"/>
<Button
android:id="@+id/bt_5"
android:layout_width="0dp"
android:layout_height="match_parent"
android:text="5"
android:textSize="30sp"
android:layout_weight="1"
android:background="@drawable/num_button_selector"/>
<Button
android:id="@+id/bt_6"
android:layout_width="0dp"
android:layout_height="match_parent"
android:text="6"
android:textSize="30sp"
android:layout_weight="1"
android:background="@drawable/num_button_selector"/>
<Button
android:id="@+id/bt_add"
android:layout_width="0dp"
android:layout_height="match_parent"
android:text="+"
android:textSize="50sp"
android:layout_weight="1"
android:background="@drawable/button_selector"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:orientation="horizontal"
android:layout_weight="1"
android:weightSum="4">
<Button
android:id="@+id/bt_1"
android:layout_width="0dp"
android:layout_height="match_parent"
android:text="1"
android:textSize="30sp"
android:layout_weight="1"
android:background="@drawable/num_button_selector"/>
<Button
android:id="@+id/bt_2"
android:layout_width="0dp"
android:layout_height="match_parent"
android:text="2"
android:textSize="30sp"
android:layout_weight="1"
android:background="@drawable/num_button_selector"/>
<Button
android:id="@+id/bt_3"
android:layout_width="0dp"
android:layout_height="match_parent"
android:text="3"
android:textSize="30sp"
android:layout_weight="1"
android:background="@drawable/num_button_selector"/>
<Button
android:id="@+id/bt_point"
android:layout_width="0dp"
android:layout_height="match_parent"
android:text="."
android:textSize="50sp"
android:layout_weight="1"
android:background="@drawable/button_selector"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_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="50sp"
android:layout_weight="1"
android:background="#f0fff0"/>
<Button
android:id="@+id/bt_0"
android:layout_width="0dp"
android:layout_height="match_parent"
android:text="0"
android:textSize="30sp"
android:layout_weight="1"
android:background="@drawable/num_button_selector"
/>
<Button
android:id="@+id/bt_equal"
android:layout_width="0dp"
android:layout_height="match_parent"
android:text="="
android:textSize="30sp"
android:layout_weight="2"
android:background="@drawable/equal_button_selector"/>
</LinearLayout>
</LinearLayout>
activity_main.xml 中的 @drawable/ 是我在写完UI界面时,发现颜色相同,button 按钮后也看不出明显的按钮反应,就用了选择器selector。先在 res 文件夹下创建一个 drawable文件夹,接着创建 selector 的文件夹,如上图我创建了三个,分别是,加减乘除等按钮的button_selector 选择器,数字的 num_button_selector 选择器,= 号的 equal_button_selector 选择器。
在这里看一下 button_select.xml 文件,其余两个类似,就是 item 的名字修改了
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:drawable="@drawable/clr_normal" android:state_pressed="false"/>
<item android:drawable="@drawable/clr_pressed" android:state_pressed="true"/>
</selector>
接着在 strings.xml 中添加 按钮 正常 以及 按下 的颜色设置即可
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">我的计算器</string>
<string name="hello_world">Hello world!</string>
<string name="action_settings">Settings</string>
<drawable name="clr_normal">#DCDCDC</drawable>
<drawable name="clr_pressed">#87CEEB</drawable>
<drawable name="num_normal">#ffffcc</drawable>
<drawable name="num_pressed">#87CEEB</drawable>
<drawable name="equal_normal">#99ccff</drawable>
<drawable name="equal_pressed">#87CEEB</drawable>
</resources>
逻辑代码
1、MainActivity 中的代码:
每点击按钮时就会执行 onclick() 方法,这里使用 switch;字符串,我们这里用 StringBuild,在没有错误信息的情况下,调用 append() 存入字符串中。至于结果的处理,我们放在点击 等号 之后,我们使用 TransToDeal 类进行处理。
package com.example.zcalculator;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity implements OnClickListener{
Button bt_0;
Button bt_1;
Button bt_2;
Button bt_3;
Button bt_4;
Button bt_5;
Button bt_6;
Button bt_7;
Button bt_8;
Button bt_9;
Button bt_clear;
Button bt_divide;
Button bt_multiply;
Button bt_del;
Button bt_minus;
Button bt_add;
Button bt_point;
Button bt_equal;
private TextView tv_input;
private StringBuilder pending = new StringBuilder();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initview();
}
private void initview() {
bt_0 = (Button) findViewById(R.id.bt_0);
bt_1 = (Button) findViewById(R.id.bt_1);
bt_2 = (Button) findViewById(R.id.bt_2);
bt_3 = (Button) findViewById(R.id.bt_3);
bt_4 = (Button) findViewById(R.id.bt_4);
bt_5 = (Button) findViewById(R.id.bt_5);
bt_6 = (Button) findViewById(R.id.bt_6);
bt_7 = (Button) findViewById(R.id.bt_7);
bt_8 = (Button) findViewById(R.id.bt_8);
bt_9 = (Button) findViewById(R.id.bt_9);
bt_clear = (Button) findViewById(R.id.bt_clear);
bt_divide = (Button) findViewById(R.id.bt_divide);
bt_multiply = (Button) findViewById(R.id.bt_multiply);
bt_del = (Button) findViewById(R.id.bt_del);
bt_minus = (Button) findViewById(R.id.bt_minus);
bt_add = (Button) findViewById(R.id.bt_add);
bt_point = (Button) findViewById(R.id.bt_point);
bt_equal = (Button) findViewById(R.id.bt_equal);
tv_input = (TextView) findViewById(R.id.tv_input);
bt_0.setOnClickListener(this);
bt_1.setOnClickListener(this);
bt_2.setOnClickListener(this);
bt_3.setOnClickListener(this);
bt_4.setOnClickListener(this);
bt_5.setOnClickListener(this);
bt_6.setOnClickListener(this);
bt_7.setOnClickListener(this);
bt_8.setOnClickListener(this);
bt_9.setOnClickListener(this);
bt_clear.setOnClickListener(this);
bt_divide.setOnClickListener(this);
bt_multiply.setOnClickListener(this);
bt_del.setOnClickListener(this);
bt_minus.setOnClickListener(this);
bt_add.setOnClickListener(this);
bt_point.setOnClickListener(this);
bt_equal.setOnClickListener(this);
}
@Override
public void onClick(View v) {
int last = 0;
if (pending.length() != 0) {
last = pending.codePointAt(pending.length() - 1);
}
switch (v.getId()) {
case R.id.bt_0:
pending = pending.append("0");
tv_input.setText(pending);
break;
case R.id.bt_1:
pending = pending.append("1");
tv_input.setText(pending);
break;
case R.id.bt_2:
pending = pending.append("2");
tv_input.setText(pending);
break;
case R.id.bt_3:
pending = pending.append("3");
tv_input.setText(pending);
break;
case R.id.bt_4:
pending = pending.append("4");
tv_input.setText(pending);
break;
case R.id.bt_5:
pending = pending.append("5");
tv_input.setText(pending);
break;
case R.id.bt_6:
pending = pending.append("6");
tv_input.setText(pending);
break;
case R.id.bt_7:
pending = pending.append("7");
tv_input.setText(pending);
break;
case R.id.bt_8:
pending = pending.append("8");
tv_input.setText(pending);
break;
case R.id.bt_9:
pending = pending.append("9");
tv_input.setText(pending);
break;
case R.id.bt_add:
pending = pending.append("+");
tv_input.setText(pending);
break;
case R.id.bt_minus:
pending = pending.append("-");
tv_input.setText(pending);
break;
case R.id.bt_multiply:
pending.append("*");
tv_input.setText(pending);
break;
case R.id.bt_divide:
pending = pending.append("/");
tv_input.setText(pending);
break;
case R.id.bt_point:
pending = pending.append(".");
tv_input.setText(pending);
break;
case R.id.bt_del:
if (pending.length() != 0) {
pending = pending.delete(pending.length() - 1, pending.length());
tv_input.setText(pending);
}
break;
case R.id.bt_clear:
pending = pending.delete(0, pending.length());
tv_input.setText(pending);
break;
case R.id.bt_equal:
if (pending.length() > 1) {
TransToDeal td = new TransToDeal();
String result;
try {
String a = td.toSuffix(pending);
result = td.dealEquation(a);
} catch (Exception e) {
result = "出错";
}
tv_input.setText(pending + "=" + "\n" + result);
pending = pending.delete(0, pending.length());
if (Character.isDigit(result.charAt(0))) {
pending = pending.append(result);
}
}
break;
default:
break;
}
}
}
2、逻辑算法
将用户输入的 pending 字符串,进行转化和处理,至于为什么要处理,,是因为------------我们把平时所用的标准四则运算表达式,即“9+(3-1)*3+10/2"叫做中缀表达式。因为所有的运算符号都在两数字的中间,现在我们的问题就是中缀到后缀的转化。中缀表达式 “9+(3-1)*3+10/2”转化为后缀表达式“9 3 1-3*+ 10 2/+”。
别人写的 后缀表达式的计算过程,大家可以看看理解一下
http://www.nowamagic.net/librarys/veda/detail/2307
下面就是 TransToDeal 类的代码 :
package com.example.zcalculator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.lang.*;
import java.util.ArrayList;
import java.util.*;
public class TransToDeal {
//使用集合定义好符号的运算优先级别
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中仅有一个结果,否则就是算错了
}
}
源码地址:https://github.com/xiayu54/Calculator
总结:
自己学习路上写的一个简单及计算器 App,希望可以对大家有帮助。
第一次写博客,写的不好的话,大家见谅,以后会改进的。另外,希望自己以后每周都可以抽时间写一篇,记录一下自己 Android 每周的学习路程,督促自己