安卓仿苹果计算器(内附完整源码)

合集下载

android实现简易计算器

android实现简易计算器

android实现简易计算器本⽂实例为⼤家分享了android实现简易计算器展⽰的具体代码,供⼤家参考,具体内容如下效果图:⼀、如图,⾸先布局计算器主页显⽰activity_main.xml<RelativeLayout xmlns:android="/apk/res/android"xmlns:tools="/tools"android:layout_width="match_parent"android:layout_height="match_parent" ><EditTextandroid:id="@+id/num1"android:layout_width="80dp"android:layout_height="wrap_content"android:inputType="number" /><TextViewandroid:id="@+id/type"android:layout_width="40dp"android:layout_height="50dp"android:layout_toRightOf="@id/num1"android:gravity="center" /><EditTextandroid:id="@+id/num2"android:layout_width="80dp"android:layout_height="wrap_content"android:layout_toRightOf="@id/num1"android:layout_marginLeft="50dp"android:inputType="number" /><TextViewandroid:id="@+id/equal"android:layout_width="80dp"android:layout_height="50dp"android:layout_toRightOf="@id/num2"android:gravity="center" /><Buttonandroid:id="@+id/add"android:layout_width="70dp"android:layout_height="wrap_content"android:layout_below="@id/num1"android:text="@string/add" /><Buttonandroid:id="@+id/sub"android:layout_width="70dp"android:layout_height="wrap_content"android:layout_toRightOf="@id/add"android:layout_alignTop="@id/add"android:text="@string/sub" /><Buttonandroid:id="@+id/mul"android:layout_width="70dp"android:layout_height="wrap_content"android:layout_toRightOf="@id/sub"android:layout_alignTop="@id/sub"android:text="@string/mul" /><Buttonandroid:id="@+id/div"android:layout_width="70dp"android:layout_height="wrap_content"android:layout_toRightOf="@id/mul"android:layout_alignTop="@id/mul"android:text="@string/div" /></RelativeLayout>⼆、计算器实现的⽅法public class CalculatorBiz {public float add(float num1,float num2){return num1+num2;}public float sub(float num1,float num2){return num1-num2;}public float mul(float num1,float num2){return num1*num2;}public float div(float num1,float num2){return num1/num2;}}三、MainActivity主要⽅法public class MainActivity extends Activity {//定义组件private EditText inputnum1;private EditText inputnum2;private TextView type;private TextView equal;private Button add;private Button sub;private Button mul;private Button div;CalculatorBiz calculator=new CalculatorBiz();@Overridepublic void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);setContentView(yout.activity_main);//查找组件inputnum1=(EditText) findViewById(R.id.num1); inputnum2=(EditText) findViewById(R.id.num2); type=(TextView) findViewById(R.id.type);equal=(TextView) findViewById(R.id.equal);add=(Button) findViewById(R.id.add);sub=(Button) findViewById(R.id.sub);mul=(Button) findViewById(R.id.mul);div=(Button) findViewById(R.id.div);type.setTextColor(Color.WHITE);equal.setTextColor(Color.WHITE);add.setOnClickListener(new OnClickListener() { @Overridepublic void onClick(View v) {String num1=inputnum1.getText().toString();String num2=inputnum2.getText().toString();float a=Float.parseFloat(num1);float b=Float.parseFloat(num2);type.setText("+");equal.setText("="+calculator.add(a, b));}});sub.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {String num1=inputnum1.getText().toString();String num2=inputnum2.getText().toString();float a=Float.parseFloat(num1);float b=Float.parseFloat(num2);type.setText("-");equal.setText("="+calculator.sub(a, b));}});mul.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {String num1=inputnum1.getText().toString();String num2=inputnum2.getText().toString();float a=Float.parseFloat(num1);float b=Float.parseFloat(num2);type.setText("*");equal.setText("="+calculator.mul(a, b));}});div.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {String num1=inputnum1.getText().toString();String num2=inputnum2.getText().toString();float a=Float.parseFloat(num1);float b=Float.parseFloat(num2);type.setText("/");equal.setText("="+calculator.div(a, b));}});}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {super.onCreateOptionsMenu(menu);menu.add(0, 1, 0, "关于");menu.add(0, 2, 1, "退出");menu.findItem(2);return true;}public boolean onOptionsItemSelected(MenuItem item){if(item.getItemId() == 1){Toast.makeText(this, "详细内容\n"+"作者:dyp\n"+"版本:version1", Toast.LENGTH_LONG).show(); }else if(item.getItemId() == 2){Toast.makeText(this, "退出\n"+"你确定退出程序?", Toast.LENGTH_LONG).show();}return super.onOptionsItemSelected(item);}}以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。

C#编写简易计算器(附源代码)超详细

C#编写简易计算器(附源代码)超详细

超详细一、因为计算器设计的控件太多,不便使用控制台应用程序完成,所以这里使用Windows窗体应用程序,并命名为Calc,如下图所示:二、向窗体中拖入需要的控件,如下图所示:(完成效果图)结果显示区(作者博客左边的文本框)是TextBox控件,并修改其name为txtShow ,按键0~9为Button控件,并将其name分别修改为btn_0、btn_1、btn_2、btn_3、btn_4、btn_5、btn_6、btn_7、btn_8、btn_9;按键【负数】的name值修改为btn_sign,按键【.】的name 修改为btn_dot,按键【+ - * /】的name值分别修改为btn_add、btn_sub、btn_mul、btn_div,按键【=】的name值修改为btn_equ,按键【倒数】的name值修改为btn_rev,按键【平方】的name值修改为btn_sqr,按键【开方】的name值修改为btn_sqrt。

右边的计算器图片空间是PictureBox,作者博客控件是LinkLabel,可以不添加,以上所有控件均可按照需求添加,只保留自己需要的按钮控件和textbox控件即可。

三、代码部分(含解释),采用switch多分支语句编写using System;using System.Drawing;using System.Collections;using ponentModel;using System.Windows.Forms;using System.Data;namespace Calc{///<summary>/// QQ:479340056 温柔一刀C#简易计算器的实现///</summary>public class CalcForm : System.Windows.Forms.Form{private System.Windows.Forms.Button btn_0;private System.Windows.Forms.Button btn_1;private System.Windows.Forms.Button btn_2;private System.Windows.Forms.Button btn_3;private System.Windows.Forms.Button btn_4;private System.Windows.Forms.Button btn_5;private System.Windows.Forms.Button btn_6;private System.Windows.Forms.Button btn_7;private System.Windows.Forms.Button btn_8;private System.Windows.Forms.Button btn_9;private System.Windows.Forms.Button btn_add;private System.Windows.Forms.Button btn_sub;private System.Windows.Forms.Button btn_mul;private System.Windows.Forms.Button btn_div;private System.Windows.Forms.Button btn_sqrt;private System.Windows.Forms.Button btn_sign;private System.Windows.Forms.Button btn_equ;private System.Windows.Forms.Button btn_dot;private System.Windows.Forms.Button btn_rev;private System.Windows.Forms.TextBox txtShow;private System.Windows.Forms.Button btn_sqr;private PictureBox pictureBox1;private LinkLabel linkLabel1;///<summary>///必需的设计器变量。

计算器Android版(源码)

计算器Android版(源码)

计算器Android版(源码)100%运行通过这是自己编写的,通过eclipse运行简易计算器Android版(源码)这是自己整理得,欢迎大家下载说明:每完成一次计算后,需先clear 清除记忆,当然也可以连算XML布局<?xml version="1.0"encoding="utf-8"?><LinearLayoutxmlns:android="/apk/res/android"android:layout_width="fill_parent"android:layout_height="fill_parent"android:orientation="vertical"><TableLayoutandroid:id="@+id/tableLayout1"android:layout_width="match_parent"android:layout_height="wrap_content"android:collapseColumns="4"><TableRowandroid:id="@+id/tableRow_et"android:layout_width="fill_parent"android:layout_height="fill_parent"><EditTextandroid:id="@+id/et"android:layout_width="fill_parent"android:layout_height="fill_parent"android:layout_span="4"android:focusable="false"android:singleLine="true"android:inputType="text"android:gravity="right"></EditText></TableRow><TableRowandroid:id="@+id/tableRow1"android:layout_width="fill_parent"android:layout_height="fill_parent"><Buttonandroid:id="@+id/bt_7"android:layout_width="40px"android:layout_height="40px"android:text="7"/><Buttonandroid:id="@+id/bt_8"android:layout_width="40px"android:layout_height="40px"android:text="8"/><Buttonandroid:id="@+id/bt_9"android:layout_width="40px"android:layout_height="40px"android:text="9"/><Buttonandroid:id="@+id/bt_back"android:layout_width="40px"android:layout_height="40px"android:text="back"/></TableRow><TableRowandroid:id="@+id/tableRow2"android:layout_width="fill_parent"android:layout_height="fill_parent"><Buttonandroid:id="@+id/bt_4"android:layout_width="40px"android:layout_height="40px"android:text="4"/><Buttonandroid:id="@+id/bt_5"android:layout_width="40px"android:layout_height="40px"android:text="5"/><Buttonandroid:id="@+id/bt_6"android:layout_width="40px"android:layout_height="40px"android:text="6"/><Buttonandroid:id="@+id/bt_divide"android:layout_width="40px"android:layout_height="40px"android:text="/"/></TableRow><TableRowandroid:id="@+id/tableRow3"android:layout_width="fill_parent"android:layout_height="fill_parent">android:layout_width="50px"android:layout_height="40px"android:text="+"/><Buttonandroid:id="@+id/bt_sub"android:layout_width="50px"android:layout_height="40px"android:text="-"/></TableRow><TableRowandroid:id="@+id/tableRow4"android:layout_width="fill_parent"android:layout_height="fill_parent"><Buttonandroid:id="@+id/bt_equal"android:layout_width="fill_parent"android:layout_height="fill_parent"android:layout_span="3"android:text="="/><Buttonandroid:id="@+id/bt_clear"android:layout_width="50px"android:layout_height="40px"android:text="clear"/></TableRow></TableLayout></LinearLayout>源代码:package android.sdk;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;import android.widget.Toast;public class Android_calculatorActivity extends Activity{private Button bt_1;private Button bt_2;private Button bt_3;private Button bt_4;private Button bt_5;private Button bt_6;private Button bt_7;private Button bt_8;private Button bt_9;private Button bt_0;private Button bt_add;private Button bt_sub; // 减private Button bt_multiply; // 乘private Button bt_divide; // 除private Button bt_back;private Button bt_equal; // 等于private Button bt_point; // 点private Button bt_clear; // 清除private EditText et_play; // 显示private String str_oper = "+"; // 运算符private StringBuffer str_display = new StringBuffer();; // 显示private String str_result; // 结果显示private double num1;private double num2;private boolean flag = true; // 小数点个数开关控制;private boolean b_sub, b_mul, b_div; // 运算符开关控制@Overridepublic void onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);setContentView(yout.main);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_add = (Button) findViewById(R.id.bt_add);bt_sub = (Button) findViewById(R.id.bt_sub);bt_multiply = (Button) findViewById(R.id.bt_multiply); bt_divide = (Button) findViewById(R.id.bt_divide);bt_back = (Button) findViewById(R.id.bt_back);bt_equal = (Button) findViewById(R.id.bt_equal);bt_point = (Button) findViewById(R.id.bt_point);bt_clear = (Button) findViewById(R.id.bt_clear);et_play = (EditText) findViewById(R.id.et);et_play.setText("0.0");bt_0.setOnClickListener(new OnClickListener(){@Overridepublic void onClick(View v){str_display.append("0");et_play.setText(str_display.toString());}});bt_1.setOnClickListener(new OnClickListener(){@Overridepublic void onClick(View v){str_display.append("1");et_play.setText(str_display.toString());}});bt_2.setOnClickListener(new OnClickListener(){@Overridepublic void onClick(View v){str_display.append("2");et_play.setText(str_display.toString());}});bt_3.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v){str_display.append("3");et_play.setText(str_display.toString());}});bt_4.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v){str_display.append("4");et_play.setText(str_display.toString());}});bt_5.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v){str_display.append("5");et_play.setText(str_display.toString());}});bt_6.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v){str_display.append("6");et_play.setText(str_display.toString());}});bt_7.setOnClickListener(new OnClickListener(){@Overridepublic void onClick(View v){str_display.append("7");et_play.setText(str_display.toString());}});bt_8.setOnClickListener(new OnClickListener(){@Overridepublic void onClick(View v){str_display.append("8");et_play.setText(str_display.toString());}});bt_9.setOnClickListener(new OnClickListener(){@Overridepublic void onClick(View v){str_display.append("9");et_play.setText(str_display.toString());}});bt_point.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v){if (flag){str_display.append(".");flag = false;}}});bt_back.setOnClickListener(new OnClickListener(){@Overridepublic void onClick(View v){if (str_display.length() != 0){str_display.deleteCharAt(str_display.length() - 1);et_play.setText(str_display.toString());}}});bt_add.setOnClickListener(new OnClickListener(){@Overridepublic void onClick(View v){str_oper = "+";if (!(str_display.toString() == "")){num1 += Double.parseDouble(str_display.toString());str_display = new StringBuffer("");}if (!(str_result == null)){num1 = Double.parseDouble(str_result);str_result = null;}et_play.setText(String.valueOf(num1));flag = true;}});bt_sub.setOnClickListener(new OnClickListener(){@Overridepublic void onClick(View v){str_oper = "-";if (!b_sub && !(str_display.toString() == "")){num1 = Double.parseDouble(str_display.toString());et_play.setText(String.valueOf(num1));str_display = new StringBuffer("");b_sub = true;} else{if (!(str_display.toString() == "")){num1 -=Double.parseDouble(str_display.toString());str_display = new StringBuffer("");}if (!(str_result == null)){num1 = Double.parseDouble(str_result);str_result = null;}et_play.setText(String.valueOf(num1));}flag = true;}});bt_multiply.setOnClickListener(new OnClickListener(){@Overridepublic void onClick(View v){str_oper = "*";if (!b_mul && !(str_display.toString() == "")){num1 = Double.parseDouble(str_display.toString());et_play.setText(String.valueOf(num1));str_display = new StringBuffer("");b_mul = true;} else{if (!(str_display.toString() == "")){num1 *=Double.parseDouble(str_display.toString());str_display = new StringBuffer("");}if (!(str_result == null)){num1 = Double.parseDouble(str_result);str_result = null;}et_play.setText(String.valueOf(num1));}flag = true;}});bt_divide.setOnClickListener(new OnClickListener(){@Overridepublic void onClick(View v){str_oper = "/";if (!b_div && !(str_display.toString() == "")){num1 = Double.parseDouble(str_display.toString());et_play.setText(String.valueOf(num1));str_display = new StringBuffer("");b_div = true;} else{if (!(str_display.toString() == "")){if(Double.parseDouble(str_display.toString()) == 0){Toast.makeText(Android_calculatorActivity.this,"除数不能为0!",Toast.LENGTH_LONG).show();} else{num1 /=Double.parseDouble(str_display.toString());str_display = new StringBuffer("");}}if (!(str_result == null)){num1 = Double.parseDouble(str_result);str_result = null;}et_play.setText(String.valueOf(num1));}flag = true;}});bt_clear.setOnClickListener(new OnClickListener(){@Overridepublic void onClick(View v){str_oper = "+";str_display = new StringBuffer("");str_result = null;num1 = 0;num2 = 0;flag = true;b_sub = false;b_mul = false;b_div = false;et_play.setText("0.0");}});bt_equal.setOnClickListener(new OnClickListener(){@Overridepublic void onClick(View v){if (str_oper.equals("+")){num2 = Double.parseDouble(str_display.toString());str_result = String.valueOf((num1 + num2));et_play.setText(str_result);str_display = new StringBuffer("");}if (str_oper.equals("-")){num2 = Double.parseDouble(str_display.toString());str_result = String.valueOf((num1 - num2));et_play.setText(str_result);str_display = new StringBuffer("");}if (str_oper.equals("*")){num2 = Double.parseDouble(str_display.toString());str_result = String.valueOf((num1 * num2));et_play.setText(str_result);str_display = new StringBuffer("");}if (str_oper.equals("/")){num2 = Double.parseDouble(str_display.toString());if (!(num2 == 0)){str_result = String.valueOf((num1 / num2));et_play.setText(str_result);} else{Toast.makeText(Android_calculatorActivity.this,"除数不能为0!", Toast.LENGTH_LONG).show();}str_display = new StringBuffer("");}}});}。

简易计算器代码

简易计算器代码
connect(button[9],SIGNAL(clicked()),this,SLOT(setOper()));
button[10] = new QPushButton(buttontext[10],this,buttontext[10]); // “—”
button[10]->setFixedSize(BUTTONWIDTH,BUTTONHEIGHT);
edit->setText(tr("%1").arg(0)); //这个函数可获取文本编辑框中光标的位置,并显示在状态栏中
//setText(tr(“%1行%2列”).arg(rowNum).arg(colNum));
initialize(); //调用初始化函数
}
void CWidget::initialize()
cwidget.cpp
#include "cwidget.h"
#define KEY_CLR "CLR"
#define KEY_ADD "+"
#define KEY_SUB "-"
#define KEY_MUL "*"
#define KEY_DIV "/"
#define KEY_EQ "="
#define KEY_0 "0"
{
delete edit;
delete *button;
delete mainLayout;
delete topLayout;
delete bottomLayout;
}
void CWidget::calculate() //响应按键“=”,调用计算功能

从零开始学android实现计算器功能示例分享(计算器源码)

从零开始学android实现计算器功能示例分享(计算器源码)

从零开始学android实现计算器功能⽰例分享(计算器源码)下⾯是效果展⽰:复制代码代码如下:<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical" ><LinearLayout android:layout_width="fill_parent"android:layout_height="wrap_content"><TextViewandroid:id="@+id/tvResult"android:layout_width="fill_parent"android:layout_height="wrap_content"android:height="50dp"android:text="@string/tvResult"/></LinearLayout><LinearLayout android:layout_width="fill_parent"android:layout_height="wrap_content"><Buttonandroid:id="@+id/btnBackspace"android:layout_width="wrap_content"android:layout_height="wrap_content"android:width="150dp"android:layout_marginLeft="10dp"android:text="@string/btnbackspace"/><Buttonandroid:id="@+id/btnCE"android:layout_width="wrap_content"android:layout_height="wrap_content"android:width="150dp"android:text="@string/btnCE"/></LinearLayout><LinearLayout android:layout_width="fill_parent"android:layout_height="wrap_content"><Buttonandroid:id="@+id/btn7"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginLeft="10dp"android:width="75dp"android:text="@string/btn7"/><Buttonandroid:id="@+id/btn8"android:layout_width="wrap_content"android:layout_height="wrap_content"android:width="75dp"android:text="@string/btn8"/><Buttonandroid:id="@+id/btnDiv"android:layout_width="wrap_content"android:layout_height="wrap_content"android:width="75dp"android:text="@string/btnDiv"/></LinearLayout><LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content"><Buttonandroid:id="@+id/btn4"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginLeft="10dp"android:width="75dp"android:text="@string/btn4"/><Buttonandroid:id="@+id/btn5"android:layout_width="wrap_content"android:layout_height="wrap_content"android:width="75dp"android:text="@string/btn5"/><Buttonandroid:id="@+id/btn6"android:layout_width="wrap_content"android:layout_height="wrap_content"android:width="75dp"android:text="@string/btn6"/><Buttonandroid:id="@+id/btnMul"android:layout_width="wrap_content"android:layout_height="wrap_content"android:width="75dp"android:text="@string/btnMul"/></LinearLayout><LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content"><Buttonandroid:id="@+id/btn1"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginLeft="10dp"android:width="75dp"android:text="@string/btn1"/><Buttonandroid:id="@+id/btn2"android:layout_width="wrap_content"android:layout_height="wrap_content"android:width="75dp"android:text="@string/btn2"/><Buttonandroid:id="@+id/btn3"android:layout_width="wrap_content"android:layout_height="wrap_content"android:width="75dp"android:text="@string/btn3"/></LinearLayout><LinearLayout android:layout_width="fill_parent"android:layout_height="wrap_content"><Buttonandroid:id="@+id/btn0"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginLeft="10dp"android:width="75dp"android:text="@string/btn0"/><Buttonandroid:id="@+id/btnC"android:layout_width="wrap_content"android:layout_height="wrap_content"android:width="75dp"android:text="@string/btnC"/><Buttonandroid:id="@+id/btnEqu"android:layout_width="wrap_content"android:layout_height="wrap_content"android:width="75dp"android:text="@string/btnEqu"/><Buttonandroid:id="@+id/btnSub"android:layout_width="wrap_content"android:layout_height="wrap_content"android:width="75dp"android:text="@string/btnSub"/></LinearLayout></LinearLayout>复制代码代码如下:package com.example.week2;import android.os.Bundle;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.TextView;import android.app.Activity;public class MainActivity extends Activity implements OnClickListener{ //声明⼀些控件Button btn0=null;Button btn1=null;Button btn2=null;Button btn3=null;Button btn4=null;Button btn5=null;Button btn6=null;Button btn7=null;Button btn8=null;Button btn9=null;Button btnBackspace=null;Button btnCE=null;Button btnMul=null;Button btnDiv=null;Button btnEqu=null;TextView tvResult=null;//声明两个参数。

java计算器源代码(仿win7)

java计算器源代码(仿win7)

java计算器源代码(仿win7)import java.awt.*;import javax.swing.*;import java.awt.event.*;class Cal extends JFrame implements ActionListener,MouseListener{JMenuBar menubar;JMenu menu_check,menu_edit,menu_help;JMenuItem menuitem_science,menuitem_check,menuitem_exit,menuitem_copy,menuitem_paste,menuitem1_copy,menuitem1_paste,menuitem_chelp,menuitem_about;JCheckBoxMenuItem menuitem_standard;JTextField ta1;int x,result2;double op1,op2,opall;private boolean end=false,flag=false,add=false,sub=false,cheng=false,chu=false,flagop2=false;JButton b_mc,b_mr,b_ms,b_mjia,b_mjian,b_tui,b_ce,b_c,b_jj,b_dui,b_7,b_8,b_9,b_chu,b_baifenhao,b_4,b_5,b_6,b_cheng,b_daoshu,b_1,b_2,b_3,b_jian,b_0,b_dian,b_jia,b_dengyu;JPanel p_all,p_button1,p_button2,p_txt,p1,p2,p3,p4,p5;private String str,resultstr;JPopupMenu popupmenu;Container con=this.getContentPane();Font font=new Font("微软雅黑",Font.PLAIN,12);Color color=new Color(120,220,120);Cal(String s){super(s);setSize(220,315);setResizable(false);setVisible(true);Dimension scr=Toolkit.getDefaultToolkit().getScreenSize();Dimension frm=this.getSize();setLocation((scr.width-frm.width)/2,(scr.height-frm.height)/2);Toolkit tk=Toolkit.getDefaultToolkit();//程序默认图标设置setIconImage(tk.createImage("D:\\sd.jpg"));setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//-----------------------------------------------------------------制作框架结构------------------------- //---------------------------------------菜单栏---------------------------menubar=new JMenuBar();menubar.setPreferredSize(new Dimension(frm.width,19));menu_check=new JMenu("查看(V)");menu_check.setFont(font);menu_check.setForeground(Color.black);menuitem_standard=new JCheckBoxMenuItem("标准型",true);menuitem_standard.setFont(font);menuitem_standard.setForeground(Color.black);menuitem_science=new JMenuItem("科学型");menuitem_science.setFont(font);menuitem_science.setForeground(Color.black);menuitem_check=new JMenuItem("查看分组");menuitem_check.setFont(font);menuitem_check.setForeground(Color.black);menuitem_exit=new JMenuItem("退出");menuitem_exit.setFont(font);menuitem_exit.setForeground(Color.black);menuitem_exit.addActionListener(this);menu_check.add(menuitem_standard);menu_check.add(menuitem_science);menu_check.addSeparator();menu_check.add(menuitem_check);menu_check.addSeparator();menu_check.add(menuitem_exit);menubar.add(menu_check);menu_edit=new JMenu("编辑(E)");menu_edit.setFont(font);menu_edit.setForeground(Color.black);menu_edit.setMnemonic(KeyEvent.VK_E);menuitem_copy=new JMenuItem("复制(C) ");menuitem_copy.setFont(font);menuitem_copy.setForeground(Color.black);menuitem_copy.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C,InputEvent.CTRL_M ASK));menuitem_copy.addActionListener(this);menuitem_paste=new JMenuItem("粘贴(P) ");menuitem_paste.setFont(font);menuitem_paste.setForeground(Color.black);menuitem_paste.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V,InputEvent.CTRL_M ASK));menuitem_paste.addActionListener(this);menu_edit.add(menuitem_copy);menu_edit.add(menuitem_paste);menubar.add(menu_edit);menu_help=new JMenu("帮助(H)");menu_help.setFont(font);menu_help.setForeground(Color.black);menuitem_chelp=new JMenuItem("查看帮助");menuitem_chelp.setFont(font);menuitem_chelp.setForeground(Color.black);menuitem_about=new JMenuItem("关于计算器");menuitem_about.setFont(font);menuitem_about.setForeground(Color.black);menuitem_about.addActionListener(this);menu_help.add(menuitem_chelp);menu_help.addSeparator();menu_help.add(menuitem_about);menubar.add(menu_help);setJMenuBar(menubar);//--------------------------------------文本框----------------------------------ta1=new JTextField("0");ta1.setFont(new Font("微软雅黑",Font.PLAIN,13));ta1.setEditable(false);//ta1.setOpaque(false);ta1.setHorizontalAlignment(JTextField.RIGHT);ta1.setPreferredSize(new Dimension((frm.width-26),45));ta1.addMouseListener(this);p_all=new JPanel();p_all.setPreferredSize(new Dimension((frm.width-6),250));//p_all.setBackground(color);p_all.setLayout(new FlowLayout(FlowLayout.CENTER,0,3));p_txt=new JPanel();p_txt.setPreferredSize(new Dimension((frm.width-6),53));p_txt.setLayout(new FlowLayout(FlowLayout.CENTER,0,7));p_txt.add(ta1);p_all.add(p_txt);con.add(p_all,BorderLayout.CENTER);//-------------------------------------按钮区----------------------------------p_button1=new JPanel();p_button1.setPreferredSize(new Dimension((frm.width-25),131)); p_button1.setLayout(new FlowLayout(FlowLayout.LEFT,0,3));p_all.add(p_button1);p1=new JPanel();p1.setPreferredSize(new Dimension((frm.width-25),127));p1.setLayout(new GridLayout(4,5,5,6));b_mc=new JButton("MC");b_mc.setFont(new Font("微软雅黑",Font.PLAIN,11));b_mc.setMargin(new Insets(0,0,0,0));b_mc.setForeground(Color.blue);b_mc.addActionListener(this);b_mr=new JButton("MR");b_mr.setFont(new Font("微软雅黑",Font.PLAIN,11));b_mr.setMargin(new Insets(0,0,0,0));b_mr.setForeground(Color.blue);b_mr.addActionListener(this);b_ms=new JButton("MS");b_ms.setFont(new Font("微软雅黑",Font.PLAIN,11));b_ms.setMargin(new Insets(0,0,0,0));b_ms.setForeground(Color.blue);b_ms.addActionListener(this);b_mjia=new JButton("M+");b_mjia.setFont(new Font("微软雅黑",Font.PLAIN,11));b_mjia.setMargin(new Insets(0,0,0,0));b_mjia.setForeground(Color.blue);b_mjia.addActionListener(this);b_mjian=new JButton("M-");b_mjian.setFont(new Font("微软雅黑",Font.PLAIN,11)); b_mjian.setMargin(new Insets(0,0,0,0));b_mjian.setForeground(Color.blue);b_mjian.addActionListener(this);b_tui=new JButton("←");b_tui.setFont(new Font("微软雅黑",Font.BOLD,14));b_tui.setMargin(new Insets(0,0,0,0));b_tui.addActionListener(this);b_tui.setForeground(Color.red);b_ce=new JButton("CE");b_ce.setFont(new Font("微软雅黑",Font.PLAIN,11));b_ce.setMargin(new Insets(0,0,0,0));b_ce.setForeground(Color.red);b_ce.addActionListener(this);b_c=new JButton("C");b_c.setFont(new Font("微软雅黑",Font.PLAIN,11));b_c.setMargin(new Insets(0,0,0,0));b_c.setForeground(Color.red);b_c.addActionListener(this);b_jj=new JButton("±");b_jj.setFont(new Font("微软雅黑",Font.PLAIN,14));b_jj.setMargin(new Insets(0,0,0,0));b_jj.setForeground(Color.red);b_jj.addActionListener(this);b_dui=new JButton("√");b_dui.setFont(new Font("微软雅黑",Font.PLAIN,11)); b_dui.setMargin(new Insets(0,0,0,0));b_dui.setForeground(Color.red);b_dui.addActionListener(this);b_7=new JButton("7");b_7.setFont(new Font("微软雅黑",Font.PLAIN,14));b_7.setMargin(new Insets(0,0,0,0));b_7.setForeground(Color.blue);b_7.setMnemonic(KeyEvent.VK_7);b_7.addActionListener(this);b_8=new JButton("8");b_8.setFont(new Font("微软雅黑",Font.PLAIN,14));b_8.setMargin(new Insets(0,0,0,0));b_8.setForeground(Color.blue);b_8.setMnemonic(KeyEvent.VK_8);b_8.addActionListener(this);b_9=new JButton("9");b_9.setMargin(new Insets(0,0,0,0));b_9.setForeground(Color.blue);b_9.setMnemonic(KeyEvent.VK_9);b_9.addActionListener(this);b_chu=new JButton("/");b_chu.setFont(new Font("微软雅黑",Font.PLAIN,14));b_chu.setMargin(new Insets(0,0,0,0));b_chu.setForeground(Color.red);b_chu.addActionListener(this);b_baifenhao=new JButton("%");b_baifenhao.setFont(new Font("微软雅黑",Font.PLAIN,11)); b_baifenhao.setMargin(new Insets(0,0,0,0));b_baifenhao.setForeground(Color.blue);b_baifenhao.addActionListener(this);b_4=new JButton("4");b_4.setFont(new Font("微软雅黑",Font.PLAIN,14));b_4.setMargin(new Insets(0,0,0,0));b_4.setForeground(Color.blue);b_4.setMnemonic(KeyEvent.VK_4);b_4.addActionListener(this);b_5=new JButton("5");b_5.setFont(new Font("微软雅黑",Font.PLAIN,14));b_5.setMargin(new Insets(0,0,0,0));b_5.setForeground(Color.blue);b_5.setMnemonic(KeyEvent.VK_5);b_5.addActionListener(this);b_6=new JButton("6");b_6.setFont(new Font("微软雅黑",Font.PLAIN,14));b_6.setMargin(new Insets(0,0,0,0));b_6.setForeground(Color.blue);b_6.setMnemonic(KeyEvent.VK_6);b_6.addActionListener(this);b_cheng=new JButton("*");b_cheng.setFont(new Font("微软雅黑",Font.PLAIN,14));b_cheng.setMargin(new Insets(0,0,0,0));b_cheng.setForeground(Color.red);b_cheng.addActionListener(this);b_daoshu=new JButton("1/x");b_daoshu.setFont(new Font("微软雅黑",Font.PLAIN,11)); b_daoshu.setMargin(new Insets(0,0,0,0));b_daoshu.setForeground(Color.blue);b_daoshu.addActionListener(this);b_1=new JButton("1");b_1.setMargin(new Insets(0,0,0,0));b_1.setForeground(Color.blue);b_1.setMnemonic(KeyEvent.VK_1);b_1.addActionListener(this);b_2=new JButton("2");b_2.setFont(new Font("微软雅黑",Font.PLAIN,14)); b_2.setMargin(new Insets(0,0,0,0));b_2.setForeground(Color.blue);b_2.setMnemonic(KeyEvent.VK_2);b_2.addActionListener(this);b_3=new JButton("3");b_3.setFont(new Font("微软雅黑",Font.PLAIN,14)); b_3.setMargin(new Insets(0,0,0,0));b_3.setForeground(Color.blue);b_3.setMnemonic(KeyEvent.VK_3);b_3.addActionListener(this);b_jian=new JButton("-");b_jian.setFont(new Font("微软雅黑",Font.PLAIN,14)); b_jian.setMargin(new Insets(0,0,0,0));b_jian.setForeground(Color.red);b_jian.addActionListener(this);b_0=new JButton("0");b_0.setFont(new Font("微软雅黑",Font.PLAIN,14)); b_0.setMargin(new Insets(0,0,0,0));b_0.setPreferredSize(new Dimension(75,27));b_0.setForeground(Color.blue);b_0.setMnemonic(KeyEvent.VK_0);b_0.addActionListener(this);JLabel L1=new JLabel();L1.setPreferredSize(new Dimension(5,3));b_dian=new JButton(".");b_dian.setFont(new Font("微软雅黑",Font.BOLD,14)); b_dian.setMargin(new Insets(0,0,0,0));b_dian.setPreferredSize(new Dimension(35,27));b_dian.setForeground(Color.blue);b_dian.addActionListener(this);JLabel L2=new JLabel();L2.setPreferredSize(new Dimension(5,3));b_jia=new JButton("+");b_jia.setFont(new Font("微软雅黑",Font.BOLD,14)); b_jia.setMargin(new Insets(0,0,0,0));b_jia.setPreferredSize(new Dimension(35,27));b_jia.setForeground(Color.red);b_jia.addActionListener(this);b_dengyu=new JButton("=");b_dengyu.setFont(new Font("微软雅黑",Font.BOLD,22));b_dengyu.setMargin(new Insets(0,0,0,0));b_dengyu.setPreferredSize(new Dimension(35,60));b_dengyu.setForeground(Color.blue);b_dengyu.addActionListener(this);p1.add(b_mc);p1.add(b_mr);p1.add(b_ms);p1.add(b_mjia);p1.add(b_mjian);p1.add(b_tui);p1.add(b_ce);p1.add(b_c);p1.add(b_jj);p1.add(b_dui);p1.add(b_7);p1.add(b_8);p1.add(b_9);p1.add(b_chu);p1.add(b_baifenhao);p1.add(b_4);p1.add(b_5);p1.add(b_6);p1.add(b_cheng);p1.add(b_daoshu);p_button1.add(p1);p_button2=new JPanel();p_button2.setPreferredSize(new Dimension((frm.width-24),65)); p_button2.setLayout(new FlowLayout(FlowLayout.LEFT,0,0));p_all.add(p_button2);p2=new JPanel();p2.setPreferredSize(new Dimension(156,65));p2.setLayout(new FlowLayout(FlowLayout.LEFT,0,1));p3=new JPanel();p3.setPreferredSize(new Dimension(39,62));p3.setLayout(new FlowLayout(FlowLayout.LEFT,4,0));p_button2.add(p2);p_button2.add(p3);p4=new JPanel();p4.setPreferredSize(new Dimension(156,27));p4.setLayout(new GridLayout(1,4,5,5));p5=new JPanel();p5.setPreferredSize(new Dimension(156,39));p5.setLayout(new FlowLayout(FlowLayout.LEFT,0,5));p2.add(p4);p2.add(p5);p4.add(b_1);p4.add(b_2);p4.add(b_3);p4.add(b_jian);p5.add(b_0);p5.add(L1);p5.add(b_dian);p5.add(L2);p5.add(b_jia);p3.add(b_dengyu);//---------------------------------------快捷菜单对象-------------------------popupmenu=new JPopupMenu(); //快捷菜单对象menuitem1_copy=new JMenuItem("复制");menuitem1_copy.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C,InputEvent.CTRL_ MASK));menuitem1_copy.addActionListener(this); //监视鼠标右击菜单”复制“popupmenu.add(menuitem1_copy);menuitem1_paste=new JMenuItem("粘贴");menuitem1_paste.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V,InputEvent.CTRL_MASK));menuitem1_paste.addActionListener(this); //监视鼠标右击菜单”粘贴“popupmenu.add(menuitem1_paste);ta1.add(popupmenu);con.validate();validate();}//---------------------------------------功能区------------------------------------public void actionPerformed(ActionEvent e){if(e.getSource()==menuitem_about){JOptionPane.showMessageDialog(null,"这是一个模仿win7的计算器!欢迎改进,\n创作者:钟作明","仿win7计算器",RMATION_MESSAGE);}if(e.getSource()==menuitem1_copy){ta1.selectAll();ta1.copy();}else if(e.getSource()==menuitem1_paste){ta1.setEditable(true);ta1.setText("");ta1.paste();ta1.setEditable(false);}else if(e.getSource()==menuitem_copy){ta1.selectAll();ta1.copy();}else if(e.getSource()==menuitem_paste){ta1.setEditable(true);ta1.setText("");ta1.paste();ta1.setEditable(false);}else if(e.getSource()==menuitem_exit){System.exit(0);}else if(e.getSource()==b_ce){ta1.setEditable(true);ta1.setText("0");ta1.setEditable(false);}else if(e.getSource()==b_c){ta1.setEditable(true);ta1.setText("0");ta1.setEditable(false);}else if(e.getSource()==b_tui){String str=ta1.getText();StringBuffer s=new StringBuffer(str);int L=s.length();try{if(L!=1){s=s.deleteCharAt(L-1);}else{s=new StringBuffer("0");}}catch(Exception e1){}ta1.setText(String.valueOf(s));}//---------------------------------------------数字键----------------------------- if(e.getSource()==b_1){addString(1);}else if(e.getSource()==b_2){addString(2);}else if(e.getSource()==b_3){addString(3);}else if(e.getSource()==b_4){addString(4);}else if(e.getSource()==b_5){addString(5);}else if(e.getSource()==b_6){addString(6);}else if(e.getSource()==b_7){addString(7);}else if(e.getSource()==b_8){addString(8);}else if(e.getSource()==b_9){addString(9);}else if(e.getSource()==b_0){addString(0);}else if(e.getSource()==b_dian){StringBuffer s1=new StringBuffer(ta1.getText());StringBuffer dian=new StringBuffer(".");if(String.valueOf(s1).indexOf(".")==-1){s1.append(dian);}ta1.setText(String.valueOf(s1));}else if(e.getSource()==b_jj){String txt=ta1.getText();int result=Integer.parseInt(txt);if(txt.indexOf("-")==-1&&txt.length()>0){if(result!=0){txt="-"+txt;}}else{StringBuffer txt1=new StringBuffer(txt);txt1=txt1.deleteCharAt(0);txt=String.valueOf(txt1);}ta1.setText(txt);}else if(e.getSource()==b_dui){str=ta1.getText();Double d=Double.parseDouble(str);if(d>=0){double d1=Math.sqrt(d);String s = String.valueOf(d1);if(s.endsWith(".0")==true){int z=(int)d1;str=String.valueOf(z);}else{str=String.valueOf(d1);}ta1.setText(str);}else{JOptionPane.showMessageDialog(null,"根号底数不能为负数","提醒", RMATION_MESSAGE);}end=true;}else if(e.getSource()==b_baifenhao){str=ta1.getText();Double d=Double.parseDouble(str);ta1.setText(""+d/100);end=true;}else if(e.getSource()==b_daoshu){str=ta1.getText();Double d=Double.parseDouble(str);if(d!=0){ta1.setText(""+1/d);}else{JOptionPane.showMessageDialog(null,"除数不能为零","提醒", RMATION_MESSAGE);}end=true;}else if(e.getSource()==b_jia){str = ta1.getText();op1 = Double.parseDouble(str);end=true;x=0;opall=op1;flagop2=false;}else if(e.getSource()==b_jian){str = ta1.getText();op1 = Double.parseDouble(str);end=true;x=1;opall=op1;flagop2=false;}else if(e.getSource()==b_cheng){str = ta1.getText();op1 = Double.parseDouble(str);end=true;x=2;opall=op1;flagop2=false;}else if(e.getSource()==b_chu){str = ta1.getText();op1 = Double.parseDouble(str);end=true;x=3;opall=op1;flagop2=false;}else if(e.getSource()==b_dengyu){str = ta1.getText();if(flagop2==false){op2 = Double.parseDouble(str);flagop2=true;}switch(x){case 0 :opall=opall+op2;String s=String.valueOf(opall);if(s.endsWith(".0")==true){result2=(int)opall;resultstr=String.valueOf(result2);}else{resultstr=String.valueOf(opall);}ta1.setText(resultstr);break;case 1 :opall=opall-op2;s=String.valueOf(opall);if(s.endsWith(".0")==true){result2=(int)opall;resultstr=String.valueOf(result2);}else{resultstr=String.valueOf(opall);}ta1.setText(resultstr);break;case 2 :opall=opall*op2;s=String.valueOf(opall);if(s.endsWith(".0")==true){result2=(int)opall;resultstr=String.valueOf(result2);}else{resultstr=String.valueOf(opall);}ta1.setText(resultstr);break;case 3 :opall=opall/op2;s=String.valueOf(opall);if(s.endsWith(".0")==true){result2=(int)opall;resultstr=String.valueOf(result2);}else{resultstr=String.valueOf(opall);}ta1.setText(resultstr);break;}end=true;}}public void addString(int num){String s=null;s=String.valueOf(num);//如果end==true;,那么屏幕清空if(end==true){ta1.setText("0");end=false;}if((ta1.getText()).equals("0")){ta1.setText(s);}else{if(ta1.getText().length()<21){str=ta1.getText()+s;ta1.setText(str);}}}public void mouseClicked(MouseEvent mec){if(mec.getModifiers()==mec.BUTTON3_MASK){popupmenu.show(ta1,mec.getX(),mec.getY());}}public void mousePressed(MouseEvent ms){}public void mouseReleased(MouseEvent md){}public void mouseEntered(MouseEvent ms){}public void mouseExited(MouseEvent mex){}public void mouseDragged(MouseEvent med){}}public class Calculator {public static void main(String[] args) {// TODO Auto-generated method stubCal jishuanji=new Cal("计算器");}}。

安卓开发的自制计算器源代码

安卓开发的自制计算器源代码

这是本人自己用安卓编写的计算器,代码的优化可能有所问题,不过大家都在学习阶段,欢迎大家批评指正,还是上源码吧。

先来运行图package com.example.nanchen.exam_1_1;import android.content.DialogInterface;import android.support.v7.app.AlertDialog;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.TextView;public class MainActivity extends AppCompatActivity implements View.OnClickListener{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 btnMul;private Button btnDiv;private Button btnDec;private Button btnEqual;private Button btnClear;private Button btnBackSpace;private TextView textView_result;double num1 = 0,num2 = 0,result = 0;//定义存储结果和两个操作数boolean isCheckEqu = false;//检测是否点击了等于int op = 0;//定义运算符boolean hasDec = false;boolean hasOp = false;@Overrideprotected void onCreate Bundle savedInstanceStatesuper.onCreate savedInstanceState;setContentView yout.activity_main;textView_result = TextView findViewById R.id.result;btn0 = Button findViewById R.id.btn0;btn1 = Button findViewById R.id.btn1;btn2 = Button findViewById R.id.btn2;btn3 = Button findViewById R.id.btn3;btn4 = Button findViewById R.id.btn4;btn5 = Button findViewById R.id.btn5;btn6 = Button findViewById R.id.btn6;btn7 = Button findViewById R.id.btn7;btn8 = Button findViewById R.id.btn8;btn9 = Button findViewById R.id.btn9;btnAdd = Button findViewById R.id.btn10;btnSub = Button findViewById R.id.btn11;btnMul = Button findViewById R.id.btn12;btnDiv = Button findViewById R.id.btn13;btnDec = Button findViewById R.id.btn14;btnEqual = Button findViewById R.id.btn15;btnClear = Button findViewById R.id.clear;btnBackSpace = Button findViewById R.id.backSpace;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;btnAdd.setOnClickListener this;btnSub.setOnClickListener this;btnDec.setOnClickListener this;btnDiv.setOnClickListener this;btnEqual.setOnClickListener this;btnMul.setOnClickListener this;btnClear.setOnClickListener this;btnBackSpace.setOnClickListener this;@Overridepublic void onClick View vswitch v.getIdcase R.id.btn0:if isCheckEqutextView_result.setText null;isCheckEqu=false;String myString0 =textView_result.getText.toString;if myString0.equals"0"myString0 = "";myString0 += "0";textView_result.setText myString0;break;case R.id.btn1:if isCheckEqutextView_result.setText null;isCheckEqu=false;String myString1 =textView_result.getText.toString;if myString1.equals"0"myString1 = "";myString1 += "1";textView_result.setText myString1;break;case R.id.btn2:if isCheckEqutextView_result.setText null;isCheckEqu=false;String myString2 =textView_result.getText.toString;if myString2.equals"0"myString2 = "";myString2 += "2";textView_result.setText myString2;break;case R.id.btn3:if isCheckEqutextView_result.setText null;isCheckEqu=false;String myString3 =textView_result.getText.toString;if myString3.equals"0"myString3 = "";myString3 += "3";textView_result.setText myString3;break;case R.id.btn4:if isCheckEqutextView_result.setText null;isCheckEqu=false;String myString4 =textView_result.getText.toString;if myString4.equals"0"myString4 = "";myString4 += "4";textView_result.setText myString4;break;case R.id.btn5:if isCheckEqutextView_result.setText null;isCheckEqu=false;String myString5 =textView_result.getText.toString;if myString5.equals"0"myString5 = "";myString5 += "5";textView_result.setText myString5;break;case R.id.btn6:if isCheckEqutextView_result.setText null;isCheckEqu=false;String myString6 =textView_result.getText.toString;if myString6.equals"0"myString6 = "";myString6 += "6";textView_result.setText myString6;break;case R.id.btn7:if isCheckEqutextView_result.setText null;isCheckEqu=false;String myString7 =textView_result.getText.toString;if myString7.equals"0"myString7 = "";myString7 += "7";textView_result.setText myString7;break;case R.id.btn8:if isCheckEqutextView_result.setText null;isCheckEqu=false;String myString8 =textView_result.getText.toString;if myString8.equals"0"myString8 = "";myString8 += "8";textView_result.setText myString8;break;case R.id.btn9:if isCheckEqutextView_result.setText null;isCheckEqu=false;String myString9 =textView_result.getText.toString;if myString9.equals"0"myString9 = "";myString9 += "9";textView_result.setText myString9;break;case R.id.btn10:if hasOpdoEqual;//显示出来当前的答案String myStringAdd =textView_result.getText.toString;if myStringAdd.equals nullreturn;num1 = Double.valueOf myStringAdd;textView_result.setText null;// 这里被清除了op = 1;isCheckEqu = false;hasDec = false;hasOp = true;break;case R.id.btn11:if hasOpdoEqual;String myStringSub =textView_result.getText.toString;if myStringSub.equals nullreturn;num1 = Double.valueOf myStringSub;textView_result.setText null;op = 2;isCheckEqu = false;hasDec = false;hasOp = true;break;case R.id.btn12:if hasOpdoEqual;String myStringMul =textView_result.getText.toString;if myStringMul.equals nullreturn;num1 = Double.valueOf myStringMul;textView_result.setText null;op = 3;isCheckEqu = false;hasDec = false;hasOp = true;break;case R.id.btn13:if hasOpdoEqual;String myStringDiv =textView_result.getText.toString;if myStringDiv.equals nullreturn;num1 = Double.valueOf myStringDiv;textView_result.setText null;op = 4;hasDec = false;isCheckEqu = false;hasOp = true;break;case R.id.btn14:if isCheckEqutextView_result.setText null;isCheckEqu=false;if hasDec//如果已经有小数点了,则弹出一个对话框AlertDialog.Builder builder = new AlertDialog.Builder MainActivity.this;builder.setTitle"警告";builder.setMessage"输入错误,一个数字不能有两个小数点!";builder.setNegativeButton"取消", new DialogInterface.OnClickListener@Overridepublic void onClick DialogInterface dialog, int which;builder.show;return;hasDec = true;String myString14 =textView_result.getText.toString;myString14 += ".";textView_result.setText myString14;break;case R.id.btn15:doEqual;hasOp = false;break;case R.id.backSpace:String myString =textView_result.getText.toString;trytextView_result.setText myString.substring0,myString.length -1;catch Exception etextView_result.setText"0";break;case R.id.clear:textView_result.setText"0";break;default:break;/*** 按下等于*/private void doEqualStringmyStringEqu=textView_result.getText.toString;if myStringEqu.equals nullreturn;num2=Double.valueOf myStringEqu;textView_result.setText null;switch opcase 0:result=num2;break;case 1:result=num1+num2;break;case 2:result=num1-num2;break;case 3:result=num1*num2;break;case 4:result=num1/num2;break;default:result=0;break;textView_result.setText String.valueOf result;isCheckEqu=true;<?xml version="1.0" encoding="utf-8"?>LinearLayoutxmlns:android="/apk/res/android"xmlns:tools="/tools"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"tools:context="com.example.nanchen.exam_1_1.MainActivity"<!--显示结果-->LinearLayoutandroid:layout_width="match_parent"android:layout_height="0dp"android:layout_weight="1"TextViewandroid:layout_width="match_parent"android:layout_height="match_parent"android:id="@+id/result"android:gravity="end"android:textSize="40sp"android:text="@string/zero"LinearLayoutLinearLayoutandroid:layout_width="match_parent"android:layout_height="0dp"android:orientation="horizontal"android:layout_weight="1"Buttonandroid:layout_width="0dp"android:layout_weight="1"android:layout_height="wrap_content"android:text="@string/clear"android:id="@+id/clear"android:textAllCaps="false"android:gravity="center"android:textSize="25sp"Buttonandroid:layout_width="0dp"android:layout_weight="1"android:layout_height="wrap_content"android:text="@string/backspace"android:id="@+id/backSpace"android:textAllCaps="false"android:gravity="center"android:textSize="25sp" LinearLayout<!--789/-->LinearLayoutandroid:layout_width="match_parent"android:layout_height="0dp"android:layout_weight="1"Buttonandroid:layout_width="0dp"android:text="@string/seven"android:id="@+id/btn7"android:textSize="30sp"android:gravity="center"android:layout_height="wrap_content"android:layout_weight="1"Buttonandroid:layout_width="0dp"android:text="@string/eight"android:id="@+id/btn8"android:textSize="30sp"android:gravity="center"android:layout_height="wrap_content"android:layout_weight="1"Buttonandroid:layout_width="0dp"android:text="@string/nine"android:id="@+id/btn9"android:textSize="30sp"android:gravity="center"android:layout_height="wrap_content"android:layout_weight="1"Buttonandroid:layout_width="0dp"android:text="@string/del"android:id="@+id/btn13"android:textSize="30sp"android:gravity="center"android:layout_height="wrap_content"android:layout_weight="1" LinearLayout<!--456*-->LinearLayoutandroid:layout_width="match_parent"android:layout_height="0dp"android:layout_weight="1"Buttonandroid:layout_width="0dp"android:text="@string/four"android:id="@+id/btn4"android:textSize="30sp"android:gravity="center"android:layout_height="wrap_content"android:layout_weight="1"Buttonandroid:layout_width="0dp"android:text="@string/five"android:id="@+id/btn5"android:textSize="30sp"android:gravity="center"android:layout_height="wrap_content"android:layout_weight="1"Buttonandroid:layout_width="0dp"android:text="@string/six"android:id="@+id/btn6"android:textSize="30sp"android:gravity="center"android:layout_height="wrap_content"android:layout_weight="1"Buttonandroid:layout_width="0dp"android:text="@string/mul"android:id="@+id/btn12"android:textSize="30sp"android:gravity="center"android:layout_height="wrap_content"android:layout_weight="1" LinearLayout<!--123- -->LinearLayoutandroid:layout_width="match_parent"android:layout_height="0dp"android:layout_weight="1"Buttonandroid:layout_width="0dp"android:text="@string/one"android:textSize="30sp"android:id="@+id/btn1"android:gravity="center"android:layout_height="wrap_content"android:layout_weight="1"Buttonandroid:layout_width="0dp"android:text="@string/two"android:id="@+id/btn2"android:textSize="30sp"android:gravity="center"android:layout_height="wrap_content"android:layout_weight="1"Buttonandroid:layout_width="0dp"android:text="@string/three"android:id="@+id/btn3"android:textSize="30sp"android:gravity="center"android:layout_height="wrap_content"android:layout_weight="1"Buttonandroid:layout_width="0dp"android:text="@string/sub"android:id="@+id/btn11"android:textSize="30sp"android:gravity="center"android:layout_height="wrap_content"android:layout_weight="1" LinearLayout<!--0.=+-->LinearLayoutandroid:layout_width="match_parent"android:layout_height="0dp"android:layout_weight="1"Buttonandroid:layout_width="0dp"android:text="@string/zero1"android:id="@+id/btn0"android:textSize="30sp"android:gravity="center"android:layout_height="wrap_content"android:layout_weight="1"Buttonandroid:layout_width="0dp"android:text="@string/dec"android:id="@+id/btn14"android:textSize="30sp"android:gravity="center"android:layout_height="wrap_content"android:layout_weight="1"Buttonandroid:layout_width="0dp"android:text="@string/equal"android:id="@+id/btn15"android:textSize="30sp"android:gravity="center"android:layout_height="wrap_content"android:layout_weight="1"Buttonandroid:layout_width="0dp"android:text="@string/add"android:id="@+id/btn10"android:textSize="30sp"android:gravity="center"android:layout_height="wrap_content"android:layout_weight="1"LinearLayoutLinearLayoutandroid:layout_weight="4"android:orientation="vertical"android:layout_width="match_parent"android:layout_height="0dp"TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:textSize="20sp"android:text="@string/string1"TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:text="@string/string2"android:textSize="20sp"LinearLayoutLinearLayout。

Android:实现一个计算器--(四则运算)

Android:实现一个计算器--(四则运算)

Android :实现⼀个计算器--(四则运算)计算器的功能介绍:Dot 的效果展⽰:侃侃 Dot:改进的地⽅:不⾜的地⽅:补充知识:android 中的事件处理步骤如何将信息显⽰到 View(EditText)上:异常的类型:Name: Dot (从某点开始,到某点结束)功能: + 、- 、* 、/ 、%(清零,退格操作)版本:1.0Dot 与其他的计算器相⽐没有太⼤的竞争⼒,甚⾄在处理⼀些极端的问题时还存在很⼤的不⾜,例如:⼤数的四则运算,对于这个问题处理的还不够到位,⽬前只能实现⼀些简单的四则运算(只能说⾃⼰的⽔平太菜,还没有掌握⼀些实质性的内容,这个是⾃⼰需要检讨的)另外:⾮常感谢 Android ⽼师教给我们的知识,使我们可以设计出第⼀款属于⾃⼰的 app.相对于最原始的设计,更新了哪些东西呢?1、改变按钮的形状,由原始的长⽅形 -- 椭圆状,使得按钮更加形象化。

2、增加背景图⽚,使⽤户的体验效果更好。

3、增加退格操作,使得⽤户在输错信息时不⽤全盘清零,可以删除刚刚写的某个字符。

1、未实现⼀些⼤数的运算。

2、当退格退完后,再按退格时会⾃动退出(不影响总体效果,但还是有那么⼀点 bug )3、⽬前两个数操作就需要 '=' ⼀下,但是可以实现多项式的运算,只是每次都需要 '='(后续会进⾏修改,逐渐完善)a 、找到事件⽬标对象(Button),通过 findViewById(),遍历⼦对象。

b 、实现view.onClickLisenter 接⼝,重写 onClick ⽅法。

c 、在事件⽬标对象上注册,btn.setOnClickListener (实现类的对象)a 、为 EditText 定义 id -- etResultb 、通过 findViewById 获取 etResult 对象c 、通过 etResult.setText() 将信息显⽰到计算器界⾯上a 、RuntimeExceptiona、RuntimeException运⾏时异常,不要求处理(但最好处理⼀下),与业务相关,⽐较主观(每个应⽤都可以采⽤⾃⼰的⽅式进⾏处理),⼀般不严重, 对效果不会产⽣太⼤的影响。

计算器Android版

计算器Android版

计算器A n d r o i d版(总12页) -CAL-FENGHAI.-(YICAI)-Company One1-CAL-本页仅作为文档封面,使用请直接删除100%运行通过这是自己编写的,通过eclipse运行简易计算器Android版(源码)这是自己整理得,欢迎大家下载说明:每完成一次计算后,需先clear 清除记忆,当然也可以连算XML布局<?xml version="1.0"encoding="utf-8"><LinearLayout xmlns:android=android:layout_width="fill_parent"android:layout_height="fill_parent"android:orientation="vertical"><TableLayoutandroid:id="@+id/tableLayout1"android:layout_width="match_parent"android:layout_height="wrap_content"android:collapseColumns="4"><TableRowandroid:id="@+id/tableRow_et"android:layout_width="fill_parent"android:layout_height="fill_parent"><EditTextandroid:id="@+id/et"android:layout_width="fill_parent"android:layout_height="fill_parent"android:layout_span="4"android:focusable="false"android:singleLine="true"android:inputType="text"android:gravity="right"></EditText></TableRow><TableRowandroid:id="@+id/tableRow1"android:layout_width="fill_parent"android:layout_height="fill_parent"><Buttonandroid:id="@+id/bt_7"android:layout_width="40px"android:layout_height="40px"android:text="7"/><Buttonandroid:id="@+id/bt_8"android:layout_width="40px"android:layout_height="40px"android:text="8"/><Buttonandroid:id="@+id/bt_9"android:layout_width="40px"android:layout_height="40px"android:text="9"/><Buttonandroid:id="@+id/bt_back"android:layout_width="40px"android:layout_height="40px"android:text="back"/></TableRow><TableRowandroid:id="@+id/tableRow2"android:layout_width="fill_parent"android:layout_height="fill_parent"> <Buttonandroid:id="@+id/bt_4"android:layout_width="40px"android:layout_height="40px"android:text="4"/><Buttonandroid:id="@+id/bt_5"android:layout_width="40px"android:layout_height="40px"android:text="5"/><Buttonandroid:id="@+id/bt_6"android:layout_width="40px"android:layout_height="40px"android:text="6"/><Buttonandroid:id="@+id/bt_divide"android:layout_width="40px"android:layout_height="40px"android:text="/"/></TableRow><TableRowandroid:id="@+id/tableRow3"android:layout_width="fill_parent"android:layout_height="fill_parent"> <Buttonandroid:id="@+id/bt_1"android:layout_width="40px"android:layout_height="40px"android:text="1"/><Buttonandroid:id="@+id/bt_2"android:layout_width="40px"android:layout_height="40px"android:text="2"/><Buttonandroid:id="@+id/bt_3"android:layout_width="40px"android:layout_height="40px"android:text="3"/><Buttonandroid:id="@+id/bt_multiply"android:layout_width="40px"android:layout_height="40px"android:text="*"/></TableRow><TableRowandroid:id="@+id/tableRow4"android:layout_width="fill_parent"android:layout_height="fill_parent"> <Buttonandroid:id="@+id/bt_0"android:layout_width="50px"android:layout_height="40px"android:text="0"/><Buttonandroid:id="@+id/bt_point"android:layout_width="50px"android:layout_height="40px"android:text="."/><Buttonandroid:id="@+id/bt_add"android:layout_width="50px"android:layout_height="40px"android:text="+"/><Buttonandroid:id="@+id/bt_sub"android:layout_width="50px"android:layout_height="40px"android:text="-"/></TableRow><TableRowandroid:id="@+id/tableRow4"android:layout_width="fill_parent"android:layout_height="fill_parent"><Buttonandroid:id="@+id/bt_equal"android:layout_width="fill_parent"android:layout_height="fill_parent"android:layout_span="3"android:text="="/><Buttonandroid:id="@+id/bt_clear"android:layout_width="50px"android:layout_height="40px"android:text="clear"/></TableRow></TableLayout></LinearLayout>源代码:package android.sdk;importimportimportimportimportimportimportpublic class Android_calculatorActivity extends Activity {private Button bt_1;private Button bt_2;private Button bt_3;private Button bt_4;private Button bt_5;private Button bt_6;private Button bt_7;private Button bt_8;private Button bt_9;private Button bt_0;private Button bt_add;private Button bt_sub; // 减private Button bt_multiply; // 乘private Button bt_divide; // 除private Button bt_back;private Button bt_equal; // 等于private Button bt_point; // 点private Button bt_clear; // 清除private EditText et_play; // 显示private String str_oper = "+"; // 运算符private StringBuffer str_display = new StringBuffer();; // 显示private String str_result; // 结果显示private double num1;private double num2;private boolean flag = true; // 小数点个数开关控制;private boolean b_sub, b_mul, b_div; // 运算符开关控制@Overridepublic void onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);setContentView(yout.main);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_add = (Button) findViewById(R.id.bt_add);bt_sub = (Button) findViewById(R.id.bt_sub);bt_multiply = (Button) findViewById(R.id.bt_multiply);bt_divide = (Button) findViewById(R.id.bt_divide);bt_back = (Button) findViewById(R.id.bt_back);bt_equal = (Button) findViewById(R.id.bt_equal);bt_point = (Button) findViewById(R.id.bt_point);bt_clear = (Button) findViewById(R.id.bt_clear);et_play = (EditText) findViewById(R.id.et);et_play.setText("0.0");bt_0.setOnClickListener(new OnClickListener(){@Overridepublic void onClick(View v){str_display.append("0");et_play.setText(str_display.toString());}});bt_1.setOnClickListener(new OnClickListener(){@Overridepublic void onClick(View v){str_display.append("1");et_play.setText(str_display.toString());}});bt_2.setOnClickListener(new OnClickListener(){@Overridepublic void onClick(View v){str_display.append("2");et_play.setText(str_display.toString());}});bt_3.setOnClickListener(new OnClickListener(){@Overridepublic void onClick(View v){str_display.append("3");et_play.setText(str_display.toString());}});bt_4.setOnClickListener(new OnClickListener(){@Overridepublic void onClick(View v){str_display.append("4");et_play.setText(str_display.toString());}});bt_5.setOnClickListener(new OnClickListener(){@Overridepublic void onClick(View v){str_display.append("5");et_play.setText(str_display.toString());}});bt_6.setOnClickListener(new OnClickListener(){@Overridepublic void onClick(View v){str_display.append("6");et_play.setText(str_display.toString());}});bt_7.setOnClickListener(new OnClickListener(){@Overridepublic void onClick(View v){str_display.append("7");et_play.setText(str_display.toString());}});bt_8.setOnClickListener(new OnClickListener(){@Overridepublic void onClick(View v){str_display.append("8");et_play.setText(str_display.toString());}});bt_9.setOnClickListener(new OnClickListener(){@Overridepublic void onClick(View v){str_display.append("9");et_play.setText(str_display.toString());}});bt_point.setOnClickListener(new OnClickListener(){@Overridepublic void onClick(View v){if (flag){str_display.append(".");flag = false;}}});bt_back.setOnClickListener(new OnClickListener(){@Overridepublic void onClick(View v){if (str_display.length() != 0){str_display.deleteCharAt(str_display.length() - 1);et_play.setText(str_display.toString());}}});bt_add.setOnClickListener(new OnClickListener(){@Overridepublic void onClick(View v){str_oper = "+";if (!(str_display.toString() == "")){num1 +=Double.parseDouble(str_display.toString());str_display = new StringBuffer("");}if (!(str_result == null)){num1 = Double.parseDouble(str_result);str_result = null;}et_play.setText(String.valueOf(num1));flag = true;}});bt_sub.setOnClickListener(new OnClickListener(){@Overridepublic void onClick(View v){str_oper = "-";if (!b_sub && !(str_display.toString() == "")){num1 =Double.parseDouble(str_display.toString());et_play.setText(String.valueOf(num1));str_display = new StringBuffer("");b_sub = true;} else{if (!(str_display.toString() == "")){num1 -=Double.parseDouble(str_display.toString());str_display = new StringBuffer("");}if (!(str_result == null)){num1 = Double.parseDouble(str_result);str_result = null;}et_play.setText(String.valueOf(num1));}flag = true;}});bt_multiply.setOnClickListener(new OnClickListener(){@Overridepublic void onClick(View v){str_oper = "*";if (!b_mul && !(str_display.toString() == "")){num1 =Double.parseDouble(str_display.toString());et_play.setText(String.valueOf(num1));str_display = new StringBuffer("");b_mul = true;} else{if (!(str_display.toString() == "")){num1 *=Double.parseDouble(str_display.toString());str_display = new StringBuffer("");}if (!(str_result == null)){num1 = Double.parseDouble(str_result);str_result = null;}et_play.setText(String.valueOf(num1));}flag = true;}});bt_divide.setOnClickListener(new OnClickListener(){@Overridepublic void onClick(View v){str_oper = "/";if (!b_div && !(str_display.toString() == "")){num1 =Double.parseDouble(str_display.toString());et_play.setText(String.valueOf(num1));str_display = new StringBuffer("");b_div = true;} else{if (!(str_display.toString() == "")){if(Double.parseDouble(str_display.toString()) == 0){Toast.makeText(Android_calculatorActivity.this,"除数不能为0!", Toast.LENGTH_LONG).show();} else{num1 /=Double.parseDouble(str_display.toString());str_display = newStringBuffer("");}}if (!(str_result == null)){num1 = Double.parseDouble(str_result);str_result = null;}et_play.setText(String.valueOf(num1));}flag = true;}});bt_clear.setOnClickListener(new OnClickListener(){@Overridepublic void onClick(View v){str_oper = "+";str_display = new StringBuffer("");str_result = null;num1 = 0;num2 = 0;flag = true;b_sub = false;b_mul = false;b_div = false;et_play.setText("0.0");}});bt_equal.setOnClickListener(new OnClickListener(){@Overridepublic void onClick(View v){if (str_oper.equals("+")){num2 =Double.parseDouble(str_display.toString());str_result = String.valueOf((num1 + num2));et_play.setText(str_result);str_display = new StringBuffer("");}if (str_oper.equals("-")){num2 =Double.parseDouble(str_display.toString());str_result = String.valueOf((num1 - num2));et_play.setText(str_result);str_display = new StringBuffer("");}if (str_oper.equals("*")){num2 =Double.parseDouble(str_display.toString());str_result = String.valueOf((num1 * num2));et_play.setText(str_result);str_display = new StringBuffer("");}if (str_oper.equals("/")){num2 =Double.parseDouble(str_display.toString());if (!(num2 == 0)){str_result = String.valueOf((num1 / num2));et_play.setText(str_result);} else{Toast.makeText(Android_calculatorActivity.this,"除数不能为0!", Toast.LENGTH_LONG).show();}str_display = new StringBuffer("");}}});}。

小程序实现计算器功能

小程序实现计算器功能

⼩程序实现计算器功能本⽂实例为⼤家分享了⼩程序实现计算器功能的具体代码,供⼤家参考,具体内容如下实现模拟⼿机上的计算器,输⼊即可运算本页⾯是做⼀个计算收款的页⾯,如果不需要下⾯的内容可以删除掉wxml<view class="calculate-box"><view class="calculate-txt">{{express}}</view><view class="result-num">={{result}}</view></view><view class="fixation-box"><view class="calculator-box"><view class="calculator-line"><view data-con='c' class='boxtn btn1 clear' catchtap="clickKeyBoard">AC</view><view data-con='←' class='boxtn btn1' catchtap="clickKeyBoard"><image src="../../../images/clear-icon.png" class="clear-icon"></image></view><view data-con='÷100' class='boxtn btn1 percent' catchtap="clickKeyBoard">%</view><view data-con='÷' class='boxtn num' catchtap="clickKeyBoard">÷</view></view><view class="calculator-line"><view data-con='7' class='boxtn btn1 num' catchtap="clickKeyBoard">7</view><view data-con='8' class='boxtn btn1 num' catchtap="clickKeyBoard">8</view><view data-con='9' class='boxtn btn1 num' catchtap="clickKeyBoard">9</view><view data-con='×' class='boxtn num' catchtap="clickKeyBoard">×</view></view><view class="calculator-line"><view data-con='4' class='boxtn btn1 num' catchtap="clickKeyBoard">4</view><view data-con='5' class='boxtn btn1 num' catchtap="clickKeyBoard">5</view><view data-con='6' class='boxtn btn1 num' catchtap="clickKeyBoard">6</view><view data-con='-' class='boxtn num' catchtap="clickKeyBoard">-</view></view><view class="calculator-line"><view data-con='1' class='boxtn btn1 num' catchtap="clickKeyBoard">1</view><view data-con='2' class='boxtn btn1 num' catchtap="clickKeyBoard">2</view><view data-con='3' class='boxtn btn1 num' catchtap="clickKeyBoard">3</view><view data-con='+' class='boxtn num' catchtap="clickKeyBoard">+</view></view><view class="calculator-line"><view data-con='0' class='boxtn btn2 num' catchtap="clickKeyBoard">0</view><view data-con='.' class='boxtn btn1 num' catchtap="clickKeyBoard">.</view><view data-con='=' class='boxtn equal' catchtap="result">=</view></view></view><view class="bottom-handle"><!-- <view class="sweep-code-verification" bindtap="sweepCodeVerification"><image src="../../../images/sweep-code-verification.png"></image><text>扫码核销</text></view> --><view style="flex: 1;font-size: 34rpx;" class="artificial-collection" bindtap="artificial_collection"><!--<image src="../../../images/artificial-collection.png"></image> --><text>⼈⼯收款</text></view><view class="payment-code" bindtap="qrcode_collection">收款码收款</view></view></view>jsdata: {express: '', //第⼀⾏的表达式result: '0', //第⼆⾏的结果calc2: {str: '', //临时字符串strList: [], //中缀表达式存储(队列先进先出)strListP: [], //后缀表达式(队列先进先出)list: [], //存放运算符的堆栈(先进后出)count: [], //计算表达式堆栈(先进后出)flag: 0 //表⽰字符串最后⼀位是否是运算符号位},isqr: false,},//给所有text或view绑定此事件,同时增加对应的⾃定义属性值clickKeyBoard(e) {let that = this;let input = e.currentTarget.dataset.con //获取每次输⼊的内容if (input == "c") {that.handleClear();} else if (input == "←") {that.handleDelete();} else {//调⽤处理字符串that.handleInfo(input);}},//处理本地⽤户的输⼊操作handleInfo(input) {if (this.data.calc2.str.length == 0) { //第⼀次点击if (input == "-" || this.checkShuZi(input)) { //为减号this.addStr(input);} else {return;}} else {if (this.data.calc2.flag == 1) { //说明最后⼀位是符号if (this.checkFuHao(input)) {this.data.calc2.str = this.data.calc2.str.substring(0, this.data.calc2.str.length - 1); //去掉最后⼀位符号,添加最新的符号进去 this.addStr(input);} else {this.addStr(input);}console.log();} else {this.addStr(input);this.result();}}this.result();},//客户点击等号了result() {//每次点击等号重新把列表给空this.data.calc2.strList.length = 0;this.data.calc2.strListP.length = 0;this.data.calc2.list.length = 0;this.data.calc2.count.length = 0;//将表达式变成中缀表达式队列this.expressToStrList(this.data.express);console.log(this.data.calc2.strList);//将中缀表达式集合赋值给临时变量let tempList = this.data.calc2.strList;this.expressToStrListP(tempList);console.log(this.data.calc2.strListP);//最终的计算let tempP = this.data.calc2.strListPfor (let m in tempP) {if (this.checkFuHao2(tempP[m])) { //不含点号的符号⽅法判断let m1 = this.data.calc2.count[0]; //取出第⼀个数据this.data.calc2.count.shift(); //取出后删除该数据let m2 = this.data.calc2.count[0];this.data.calc2.count.shift();// console.log('m1是' +m1);// console.log('m2是' + m2);// console.log('运算符是' + tempP[m]);// console.log('计算结果是:' + this.countDetail(m2, tempP[m], m1));this.data.calc2.count.unshift(this.countDetail(m2, tempP[m], m1)); //将计算结果放到count中 } else {this.data.calc2.count.unshift(tempP[m]) //将数字压进去}}console.log('最终的计算结果是' + parseFloat(this.data.calc2.count[0]).toFixed(2));this.setData({result: this.data.calc2.count[0]});},//实际具体计算countDetail(e1, e2, e3) {let result = 0.0;console.log(e1);console.log(e2);console.log(e3);try {if (e2 == "×") {if (typeof(e1) != "undefined") {result = parseFloat(e1) * parseFloat(e3);} else {result = parseFloat(e3);}} else if (e2 == "÷") {if (typeof(e1) != "undefined") {result = parseFloat(e1) / parseFloat(e3);} else {result = parseFloat(e3);}} else if (e2 == "%") {if (typeof(e1) != "undefined") {result = parseFloat(e1) / parseFloat(e3);} else {result = parseFloat(e3);}} else if (e2 == "+") {if (typeof(e1) != "undefined") {result = parseFloat(e1) + parseFloat(e3);} else {result = parseFloat(e3);}} else {if (typeof (e1) != "undefined") {result = parseFloat(e1) - parseFloat(e3);} else {result = parseFloat(e3);}}} catch (error) {}return result;},//将中缀表达式集合转变为后缀表达式集合expressToStrListP(tempList) {for (let item in tempList) {if (this.checkFuHao2(tempList[item])) { //不含点号的符号⽅法判断if (this.data.calc2.list.length == 0) {this.data.calc2.list.unshift(tempList[item]); //直接添加添加运算符} else {if (this.checkFuHaoDX(this.data.calc2.list[0], tempList[item])) {for (let x in this.data.calc2.list) {this.data.calc2.strListP.push(this.data.calc2.list[x]); //将运算符都放到listP中}this.data.calc2.list.length = 0; //循环完把list置空this.data.calc2.list.unshift(tempList[item]); //加新元素进去} else {this.data.calc2.list.unshift(tempList[item]); //直接添加添加运算符}}} else {this.data.calc2.strListP.push(tempList[item]); //数字直接加到后缀集合中}}//循环完有可能最后⼀个是数字了,取到的不是字符,那么运算符⾥剩余的还的加到listP中if (this.data.calc2.list.length > 0) {for (let x in this.data.calc2.list) {this.data.calc2.strListP.push(this.data.calc2.list[x]); //将运算符都放到listP中}this.data.calc2.list.length = 0; //循环完把list置空}},//判断两个运算符的优先级(m1是list集合中最后加进去的那个元素⽐较将要进来的元素,如果m1⽐m2⼤,弹出list集合到listp中,再把m2加到list中,否则直接将m2加⼊list) checkFuHaoDX(m1, m2) {if ((m1 == "%" || m1 == "×" || m1 == "÷") && (m2 == "-" || m2 == "+")) {return true;} else {return false;}},//将字符串表达式变成中缀队列expressToStrList(express) {let temp = ''; //定义临时变量//将表达式改为中缀队列for (let i = 0; i < express.length; i++) {if (i == 0 && express[i] == "-") {temp = temp + express[i];} else {if (this.checkShuZi2(express[i])) { //如果i是数字temp = temp + express[i];} else {if (temp.length > 0) {if (express[i] == ".") {temp = temp + express[i];} else {this.data.calc2.strList.push(parseFloat(temp));temp = '';this.data.calc2.strList.push(express[i]);}} else {temp = temp + express[i];}}}}//循环到最后再看temp中有没有数字了,如果有加进来if (temp.length > 0 && this.checkShuZi(temp.substring(temp.length - 1))) {this.data.calc2.strList.push(parseFloat(temp));temp = '';}},//处理客户输⼊清除键handleClear() {this.data.calc2.str = '';this.data.calc2.strList.length = 0;this.data.calc2.strListP.length = 0;this.data.calc2.list.length = 0;this.data.calc2.count.length = 0;this.data.calc2.minusFlag = 0;this.setData({express: '',result: ''});},//处理客户输⼊回退键handleDelete() {let that = this;let str = that.data.calc2.str;if (str.length > 0) {str = str.substring(0, str.length - 1);that.data.calc2.str = str;that.setData({express: str,});} else {return;}},//判断是否是运算符(含点号,⽤在组织表达式时 .不能重复输⼊)checkFuHao(input) {if (input == "-" || input == "+" || input == "÷" || input == "%" || input == "×" || input == ".") { return true;} else {return false;}},//判断是否是运算符(不含点号)checkFuHao2(input) {if (input == "-" || input == "+" || input == "÷" || input == "%" || input == "×") {return true;} else {return false;}},//判断是否是数字checkShuZi(input) {if (input == "0" || input == "1" || input == "2" ||input == "3" || input == "4" || input == "5" ||input == "6" || input == "7" || input == "8" || input == "9") {return true;} else {return false;}},//判断是否是数字(包含.号,⽤在表达式转中缀⽅法中)checkShuZi2(input) {if (input == "0" || input == "1" || input == "2" ||input == "3" || input == "4" || input == "5" ||input == "6" || input == "7" || input == "8" || input == "9" || input == ".") {return true;} else {return false;}},//给字符串添加新字符(直接追加在判断是否要改变变量flag)addStr(input) {this.data.calc2.str = this.data.calc2.str + input;if (this.checkFuHao(input)) {this.data.calc2.flag = 1; //设置标记位位1} else {this.data.calc2.flag = 0;}this.setData({express: this.data.calc2.str});},wxss/* pages/index/collect-money/collect-money.wxss */page {background-color: #f8f8f8;}.bottom-handle {height: 100rpx;width: 100%;display: flex;align-items: center;}.fixation-box {position: fixed;bottom: 0;width: 750rpx;}.sweep-code-verification {background: #fff;border-top: 1rpx solid #e3e3e3;width: 220rpx;color: #333;}.artificial-collection, .sweep-code-verification {height: 100%;display: flex;flex-direction: column;align-items: center;font-size: 24rpx;justify-content: center;}.artificial-collection {background: #f3b055;width: 248rpx;color: #fff;}.payment-code {background-image: linear-gradient(203deg, #6f6f6f 0%, #3c3c3c 96%); flex: 1;font-size: 34rpx;color: #fff;text-align: center;line-height: 100rpx;}.sweep-code-verification image {width: 40rpx;height: 40rpx;}.artificial-collection image {width: 40rpx;height: 40rpx;}.calculator-box {background-color: #fff;}.calculator-line {display: flex;align-items: center;}.boxtn {width: 25%;height: 154rpx;border-left: none;display: flex;align-items: center;justify-content: center;}.calculator-box .calculator-line:last-child {border-bottom: none;}.calculator-line {border-bottom: 1rpx solid #dedede;}.btn1, .btn2 {border-right: 1rpx solid #dedede;}.btn2 {width: 50%;}.equal {background: #f3b055;font-size: 61rpx;color: #fff;}.num {font-size: 60rpx;color: #000;}.clear {font-size: 48rpx;color: #f3b055;}.percent {font-size: 60rpx;color: #000;}.charge-content {background: #fff;border-radius: 24rpx;width: 540rpx;display: flex;flex-direction: column;align-items: center;}.charge-title {background: #f3b055;border-radius: 12px 12px 0 0; width: 100%;height: 92rpx;font-size: 34rpx;line-height: 92rpx;text-align: center;color: #fff;}.charge-money {font-size: 60rpx;color: #333;line-height: 84rpx;margin-top: 35rpx;}.charge-propmt {font-size: 28rpx;color: #999;line-height: 42rpx;padding-bottom: 40rpx;}.charge-btn {display: flex;align-items: center;height: 100rpx;border-top: 1rpx solid #ddd;width: 100%;}.charge-cancel, .charge-confirm { flex: 1;text-align: center;line-height: 100rpx;font-size: 34rpx;}.charge-cancel {color: #999;border-right: 1rpx solid #ddd;}.charge-confirm {color: #f3b055;}.successful-content {background: #fff;border-radius: 24rpx;width: 540rpx;display: flex;flex-direction: column;align-items: center;}.success-icon {width: 120rpx;margin-top: 45rpx;height: 120rpx;}.successful-title {font-size: 34rpx;color: #333;line-height: 42rpx;padding: 30rpx 0;font-weight: 600;}.clear-icon {width: 80rpx;height: 80rpx;}.calculate-box {position: fixed;top: 0;bottom: 875rpx;width: 100%;display: flex;flex-direction: column;align-items: flex-end;padding: 0 50rpx;}.result-num {font-size: 88rpx;color: #333;line-height: 124rpx;}.calculate-txt {font-size: 60rpx;color: #333;line-height: 84rpx;margin-top: auto;word-wrap: break-word;text-align: right;word-break: break-all;text-overflow: -o-ellipsis-lastline;overflow: hidden;text-overflow: ellipsis;display: -webkit-box;-webkit-line-clamp: 2;-webkit-box-orient: vertical;}.suspend-box{height: 64rpx;background-color: rgba(0, 0, 0, .5);position: fixed;top: 70rpx;left: 0;color: #fff;display: flex;align-items: center;font-size: 24rpx;padding: 0 20rpx;border-radius: 0 100rpx 100rpx 0;z-index: 9;}.close-suspend{width: 30rpx;height: 30rpx;}以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。

Android实现横屏切换科学计算器

Android实现横屏切换科学计算器

Android实现横屏切换科学计算器本⽂实例为⼤家分享了Android实现横屏切换科学计算器的具体代码,供⼤家参考,具体内容如下简单计算器设计,实现以下功能:1、竖屏时能实现基本的加减乘除运算、回退和清空输⼊。

2、横屏时变为科学计算器,实现函数计算、进制换算等功能。

输⼊计算公式,按等号键输出计算结果。

3、公式输⼊和结果显⽰区⽀持长按弹出复制、粘贴功能。

4、使⽤计算器过程中应不弹出软键盘。

5、可以通过进度条实时调整计算结果保留的⼩数点后位数,或者通过⾳量键完成同样的效果。

6、实现附加功能:三⾓函数、阶乘、XY、⼋进制转换、⼗六进制转换、√(Y&X)及括号,如sin(90)。

竖屏简单计算器竖屏界⾯设计xml代码:<?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="/apk/res/android"xmlns:app="/apk/res-auto"xmlns:tools="/tools"android:layout_width="match_parent"android:layout_height="match_parent"android:background="@color/white"tools:context=".MainActivity"><LinearLayoutandroid:id="@+id/layout1"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"><EditTextandroid:id="@+id/textView"android:layout_width="match_parent"android:height="5dp"android:gravity="center|end"android:textColor="@color/black"android:textSize="50sp"android:text=""android:enabled="true"android:textCursorDrawable="@null"android:background="@null"android:inputType="none"android:textIsSelectable="true"android:layout_height="5dp" /><SeekBarandroid:id="@+id/seekBar"style="@style/Widget.AppCompat.SeekBar.Discrete"android:layout_width="match_parent"android:layout_height="6dp"android:layout_marginBottom="5dp"android:progressDrawable="@drawable/bar"android:min="1"android:max="10"/><androidx.gridlayout.widget.GridLayoutandroid:layout_width="match_parent"android:layout_height="match_parent"app:useDefaultMargins="false"app:columnCount="4"app:rowCount="5"><Buttonandroid:id="@+id/button5"android:background="@drawable/func_btn_style"android:textSize="24sp"android:textColor="#0000ff"android:text="C" /><Buttonandroid:id="@+id/button6"android:background="@drawable/func_btn_style"android:textSize="24sp"android:textColor="#0000ff"<Buttonandroid:id="@+id/button7"android:background="@drawable/func_btn_style" android:textSize="24sp"android:textColor="#0000ff"android:text="×" /><Buttonandroid:id="@+id/button8"android:background="@drawable/func_btn_style" android:textSize="24sp"android:textColor="#0000ff"android:text="◁" /><Buttonandroid:id="@+id/button9"android:background="@drawable/buttonstyle"android:textSize="24sp"android:textColor="@color/black"android:text="1" /><Buttonandroid:id="@+id/button10"android:background="@drawable/buttonstyle"android:textSize="24sp"android:textColor="@color/black"android:text="2" /><Buttonandroid:id="@+id/button11"android:background="@drawable/buttonstyle"android:textSize="24sp"android:textColor="@color/black"android:text="3" /><Buttonandroid:id="@+id/button12"android:background="@drawable/func_btn_style" android:textSize="24sp"android:textColor="#0000ff"android:text="-" /><Buttonandroid:id="@+id/button13"android:background="@drawable/buttonstyle"android:textSize="24sp"android:textColor="@color/black"android:text="4" /><Buttonandroid:id="@+id/button14"android:background="@drawable/buttonstyle"android:textSize="24sp"android:textColor="@color/black"android:text="5" /><Buttonandroid:id="@+id/button15"android:background="@drawable/buttonstyle"android:textSize="24sp"android:textColor="@color/black"android:text="6" /><Buttonandroid:id="@+id/button16"android:background="@drawable/func_btn_style" android:textSize="24sp"android:textColor="#0000ff"android:text="+" /><Buttonandroid:id="@+id/button17"android:background="@drawable/buttonstyle"android:textSize="24sp"android:textColor="@color/black"android:text="7" /><Buttonandroid:id="@+id/button18"android:background="@drawable/buttonstyle"android:textSize="24sp"android:text="8" /><Buttonandroid:id="@+id/button19"android:background="@drawable/buttonstyle"android:textSize="24sp"android:textColor="@color/black"android:text="9" /><Buttonandroid:id="@+id/button20"android:background="@drawable/equals_button_style"android:textSize="24sp"android:textColor="@color/white"app:layout_rowSpan="2"android:text="=" /><Buttonandroid:id="@+id/button21"android:background="@drawable/buttonstyle"android:textSize="24sp"android:textColor="@color/black"android:text="%" /><Buttonandroid:id="@+id/button22"android:background="@drawable/buttonstyle"android:textSize="24sp"android:textColor="@color/black"android:text="0" /><Buttonandroid:id="@+id/button23"android:background="@drawable/buttonstyle"android:textSize="24sp"android:textColor="@color/black"android:text="." /></androidx.gridlayout.widget.GridLayout></LinearLayout></androidx.constraintlayout.widget.ConstraintLayout>竖屏效果图:(调节进度条或通过⾳量键可以调节⼩数点位数唷!)横屏xml代码:<?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="/apk/res/android" xmlns:app="/apk/res-auto"xmlns:tools="/tools"android:layout_width="match_parent"android:layout_height="match_parent"android:background="@color/white"tools:context=".MainActivity"><!-- 结果显⽰框 --><LinearLayoutandroid:id="@+id/layout2"android:layout_height="match_parent"android:orientation="vertical"><EditTextandroid:id="@+id/input"android:layout_width="match_parent"android:layout_height="75dp"android:cursorVisible="false"android:gravity="right|center_vertical"android:enabled="true"android:textCursorDrawable="@null"android:background="@null"android:inputType="none"android:textSize="30sp"android:textIsSelectable="true"/><!-- 接下去采TableRow的格式进⾏布局设计 --><androidx.gridlayout.widget.GridLayoutandroid:layout_width="match_parent"android:layout_height="match_parent"app:rowCount="7"app:columnCount="6"><TextViewandroid:id="@+id/M"android:layout_height="wrap_content"android:gravity="center"android:text=" Mem : " /><TextViewandroid:id="@+id/mem"android:layout_height="wrap_content"app:layout_columnSpan="5"android:gravity="left"android:text=" 0" /><SeekBarandroid:id="@+id/seekBar"style="@style/Widget.AppCompat.SeekBar.Discrete" android:layout_width="match_parent"android:progressDrawable="@drawable/bar"android:layout_marginBottom="5dp"android:layout_height="6dp"app:layout_columnSpan="6"android:min="1"android:max="10"/><TextViewandroid:id="@+id/_drg"android:layout_height="wrap_content"android:textSize="18sp"android:gravity="center"android:background="@drawable/func_btn_style"android:text="DEG" /><Buttonandroid:id="@+id/drg"android:layout_height="wrap_content"android:background="@drawable/func_btn_style"android:textSize="18sp"android:textColor="#888"android:text="DRG" /><Buttonandroid:id="@+id/mc"android:layout_height="wrap_content"app:layout_columnSpan="2"android:background="@drawable/func_btn_style"android:textColor="#888"android:textSize="18sp"android:text="MC" /><Buttonandroid:id="@+id/c"android:layout_height="wrap_content"app:layout_columnSpan="2"android:background="@drawable/func_btn_style"android:textColor="#00b5e2"android:textSize="18sp"android:text="C" />android:text="sin"android:background="@drawable/func_btn_style" android:textSize="18sp"android:textColor="#888"android:textAllCaps="false"/><Buttonandroid:id="@+id/cos"android:layout_height="wrap_content"android:textAllCaps="false"android:background="@drawable/func_btn_style" android:textSize="18sp"android:textColor="#888"android:text="cos" /><Buttonandroid:id="@+id/tan"android:layout_height="wrap_content"android:textAllCaps="false"android:textSize="18sp"android:textColor="#888"android:background="@drawable/func_btn_style" android:text="tan" /><Buttonandroid:id="@+id/factorial"android:layout_height="wrap_content"android:textAllCaps="false"android:textSize="18sp"android:textColor="#888"android:background="@drawable/func_btn_style" android:text="n!" /><Buttonandroid:id="@+id/bksp"android:layout_height="wrap_content"android:layout_weight="1"app:layout_columnSpan="2"android:background="@drawable/func_btn_style" android:textColor="#00b5e2"android:textSize="18sp"android:text="◁" /><Buttonandroid:id="@+id/one"android:layout_height="wrap_content"android:background="@drawable/buttonstyle"android:textSize="18sp"android:text="1" /><Buttonandroid:id="@+id/two"android:layout_height="wrap_content"android:background="@drawable/buttonstyle"android:textSize="18sp"android:text="2" /><Buttonandroid:id="@+id/three"android:layout_height="wrap_content"android:background="@drawable/buttonstyle"android:textSize="18sp"android:text="3" /><Buttonandroid:id="@+id/divide"android:layout_height="wrap_content"android:background="@drawable/func_btn_style" android:textColor="#00b5e2"android:textSize="18sp"android:text="÷" /><Buttonandroid:id="@+id/left"android:layout_height="wrap_content"android:background="@drawable/func_btn_style" android:text="("android:textColor="#888"android:textSize="18sp"/>android:background="@drawable/func_btn_style" android:text=")"android:textColor="#888"android:textSize="18sp"/><Buttonandroid:id="@+id/four"android:layout_height="wrap_content"android:background="@drawable/buttonstyle"android:text="4"android:textSize="18sp"/><Buttonandroid:id="@+id/five"android:layout_height="wrap_content"android:background="@drawable/buttonstyle"android:text="5"android:textSize="18sp"/><Buttonandroid:id="@+id/six"android:layout_height="wrap_content"android:background="@drawable/buttonstyle"android:text="6"android:textSize="18sp"/><Buttonandroid:id="@+id/mul"android:layout_height="wrap_content"android:background="@drawable/func_btn_style" android:textColor="#00b5e2"android:text="×"android:textSize="18sp"/><Buttonandroid:id="@+id/sqrt"android:layout_height="wrap_content"android:background="@drawable/func_btn_style" android:text="√"android:textColor="#888"android:textSize="18sp"/><Buttonandroid:id="@+id/square"android:layout_height="wrap_content"android:background="@drawable/func_btn_style" android:text="^"android:textColor="#888"android:textSize="18sp"/><Buttonandroid:id="@+id/seven"android:layout_height="wrap_content"android:background="@drawable/buttonstyle"android:text="7"android:textSize="18sp"/><Buttonandroid:id="@+id/eight"android:layout_height="wrap_content"android:background="@drawable/buttonstyle"android:text="8"android:textSize="18sp"/><Buttonandroid:id="@+id/nine"android:layout_height="wrap_content"android:background="@drawable/buttonstyle"android:text="9"android:textSize="18sp"/><Buttonandroid:id="@+id/sub"android:layout_height="wrap_content"android:background="@drawable/func_btn_style" android:textColor="#00b5e2"android:text="-"android:textSize="18sp"/>android:id="@+id/log"android:layout_height="wrap_content"android:textAllCaps="false"android:background="@drawable/func_btn_style"android:text="log"android:textColor="#888"android:textSize="18sp"/><Buttonandroid:id="@+id/ln"android:layout_height="wrap_content"android:textAllCaps="false"android:background="@drawable/func_btn_style"android:text="ln"android:textColor="#888"android:textSize="18sp"/><Buttonandroid:id="@+id/dot"android:layout_height="wrap_content"android:background="@drawable/buttonstyle"android:text="."android:textSize="18sp"/><Buttonandroid:id="@+id/zero"android:layout_height="wrap_content"android:background="@drawable/buttonstyle"android:text="0"android:textSize="18sp"/><LinearLayoutandroid:id="@+id/linear"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="horizontal" ><Buttonandroid:id="@+id/bd"android:layout_height="match_parent"android:background="@drawable/buttonstyle"android:text="D"android:textSize="18sp"android:layout_weight="1"android:layout_width="match_parent" /><Buttonandroid:id="@+id/db"android:layout_width="match_parent"android:layout_height="match_parent"android:background="@drawable/buttonstyle"android:textSize="18sp"android:layout_weight="1"android:text="B" /></LinearLayout><Buttonandroid:id="@+id/add"android:layout_height="wrap_content"android:background="@drawable/func_btn_style"android:textColor="#00b5e2"android:text="+"android:textSize="18sp"/><Buttonandroid:id="@+id/equal"android:layout_height="wrap_content"android:background="@drawable/equals_button_style" android:textColor="#ffffff"app:layout_columnSpan="2"android:text="="android:textSize="18sp"/><TextViewandroid:id="@+id/T"android:layout_height="wrap_content"android:text="提⽰ : "app:layout_columnSpan="6"/><TextViewandroid:layout_height="wrap_content"android:text="欢迎使⽤!"app:layout_columnSpan="6"/></androidx.gridlayout.widget.GridLayout></LinearLayout></androidx.constraintlayout.widget.ConstraintLayout>横屏效果图:Java代码如下:package com.zjw;import android.app.Activity;import android.content.ClipboardManager;import android.content.res.Configuration;import android.graphics.Point;import android.os.Bundle;import android.text.Editable;import android.text.method.KeyListener;import android.util.Log;import android.view.Display;import android.view.KeyEvent;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.LinearLayout;import android.widget.SeekBar;import android.widget.TextView;import android.widget.Toast;import androidx.annotation.NonNull;import java.math.BigDecimal;import java.util.StringTokenizer;public class MainActivity extends Activity {/*** 定义变量*///舍⼊精度public static final int[] DEF_DIV_SCALE = {17}; //初始化显⽰数据private final String[] init =new String[1];//显⽰框private EditText input;// ⽤于显⽰输出结果//划动条private SeekBar seekBar;//普通控件及变量private Button div, mul, sub, add, equal, sin, cos, tan, log, ln, sqrt,square, factorial, bksp, left, right, dot, bd, db, drg, mc, c;public String str_old;public String str_new;public boolean vbegin = true;// 控制输⼊,true为重新输⼊,false为接着输⼊public boolean drg_flag = true;// true为⾓度,false为弧度public double pi = 4 * Math.atan(1);// π值public boolean tip_lock = true;// true为正确,可以继续输⼊,false错误,输⼊锁定 public boolean equals_flag = true;// 是否在按下=之后输⼊,true为之前,false为之后 //定义ContextMenu中每个菜单选项的Idfinal int Menu_1 = Menu.FIRST;final int Menu_2 = Menu.FIRST + 1;private ClipboardManager mClipboard = null;public boolean onCreateOptionsMenu(Menu menu) {//导⼊菜单布局getMenuInflater().inflate(R.menu.main, menu);return true;}public boolean onOptionsItemSelected(MenuItem item) {//创建菜单项的点击事件switch (item.getItemId()) {case R.id.menu_setting:Toast.makeText(this, "点击了设置", Toast.LENGTH_SHORT).show();break;case R.id.menu_out:// Toast.makeText(this, "点击了退出", Toast.LENGTH_SHORT).show();android.os.Process.killProcess(android.os.Process.myPid());//获取PIDSystem.exit(0);break;default:break;}return super.onOptionsItemSelected(item);}/***onCreate*/@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);//切换布局后调⽤,初始化显⽰if(savedInstanceState!=null){init[0] = savedInstanceState.getString("exp");equals_flag = false;}//屏幕⽅向监听int orientation = getResources().getConfiguration().orientation;if (orientation == Configuration.ORIENTATION_LANDSCAPE) {// 横屏内容setContentView(yout.activity_main2);InitWigdet();AllWigdetListener();}else if (orientation == Configuration.ORIENTATION_PORTRAIT) {// 竖屏内容setContentView(yout.activity_main);input = (EditText)findViewById(R.id.textView);input.setText(init[0]);seekBar = (SeekBar) findViewById(R.id.seekBar);seekBar.setProgress(DEF_DIV_SCALE[0]);seekBar.setOnSeekBarChangeListener(onSeekBarChangeListener);Display defaultDisplay = getWindowManager().getDefaultDisplay();Point point = new Point();defaultDisplay.getSize(point);Integer x = point.x;Integer y = point.y;input.setKeyListener(new KeyListener() {@Overridepublic int getInputType() {}@Overridepublic boolean onKeyDown(View view, Editable editable, int i, KeyEvent keyEvent) {return false;}@Overridepublic boolean onKeyUp(View view, Editable editable, int i, KeyEvent keyEvent) {return false;}@Overridepublic boolean onKeyOther(View view, Editable editable, KeyEvent keyEvent) {return false;}@Overridepublic void clearMetaKeyState(View view, Editable editable, int i) {}});View.OnClickListener onClearListener = new View.OnClickListener() {@Overridepublic void onClick(View view) {input.setText("");}};View.OnClickListener onClearLastListener = new View.OnClickListener() {@Overridepublic void onClick(View view) {String s = input.getText().toString();int len = s.length();if(len>0) {s = s.substring(0, len - 1);input.setText(s);}}};View.OnClickListener onEXPListener = new View.OnClickListener() {@Overridepublic void onClick(View view) {Button temp = (Button)view;String s = temp.getText().toString();String show = input.getText().toString();int len = show.length();if(show.length()==0){if(s.equals("+")||s.equals("×")||s.equals("÷")) return;}if((show.endsWith("+"))||(show.endsWith("-"))||(show.endsWith("×"))||(show.endsWith("÷"))||(show.endsWith("."))){ if(s.equals("+")||s.equals("×")||s.equals("÷")||s.equals("-")||(s.equals("."))){show = show.substring(0,len-1) + s;input.setText(show);}else{input.append(s);}}else{input.append(s);}}};View.OnClickListener onEXECListener = new View.OnClickListener() {@Overridepublic void onClick(View view) {String s = input.getText().toString();if(s.length()==0) return;s = s.replace("×","*");s = s.replace("÷","/");s = s.replace("%","");if((s.endsWith("+"))||(s.endsWith("-"))||(s.endsWith("*"))||(s.endsWith("/"))||(s.endsWith(".")))return;try{String re = Calculator.conversion(s);re = round(re,DEF_DIV_SCALE[0]);if(re.indexOf(".") > 0){re = re.replaceAll("0+?$", "");//去掉多余的0re = re.replaceAll("[.]$", "");//如最后⼀位是.则去掉}input.setText(re);}catch (Exception e){Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_SHORT).show();}}};View.OnClickListener onPERCENTCListener = new View.OnClickListener() {@Overridepublic void onClick(View view) {String s = input.getText().toString();if(s.length()==0) return;s = s.replace("×","*");s = s.replace("÷","/");s = s.replace("%","");if((s.endsWith("+"))||(s.endsWith("-"))||(s.endsWith("*"))||(s.endsWith("/"))||(s.endsWith("."))) return;s = s+"/100";try{String re = Calculator.conversion(s);re = round(re,DEF_DIV_SCALE[0]);if(re.indexOf(".") > 0){re = re.replaceAll("0+?$", "");//去掉多余的0re = re.replaceAll("[.]$", "");//如最后⼀位是.则去掉}input.setText(re+"%");}catch (Exception e){Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_SHORT).show();input.setText("");}}};input.getLayoutParams().height = 2*y/7;Button button5 = (Button)findViewById(R.id.button5); button5.getLayoutParams().width = x/4 ;button5.getLayoutParams().height = y/8;Button button6 = (Button)findViewById(R.id.button6); button6.getLayoutParams().width = x/4 ;button6.getLayoutParams().height = y/8;Button button7 = (Button)findViewById(R.id.button7); button7.getLayoutParams().width = x/4 ;button7.getLayoutParams().height = y/8;Button button8 = (Button)findViewById(R.id.button8); button8.getLayoutParams().width = x/4 ;button8.getLayoutParams().height = y/8;Button button9 = (Button)findViewById(R.id.button9); button9.getLayoutParams().width = x/4 ;button9.getLayoutParams().height = y/8;Button button10 = (Button)findViewById(R.id.button10); button10.getLayoutParams().width = x/4 ;button10.getLayoutParams().height = y/8;Button button11 = (Button)findViewById(R.id.button11); button11.getLayoutParams().width = x/4 ;button11.getLayoutParams().height = y/8;Button button12 = (Button)findViewById(R.id.button12); button12.getLayoutParams().width = x/4 ;button12.getLayoutParams().height = y/8;Button button13 = (Button)findViewById(R.id.button13); button13.getLayoutParams().width = x/4 ;button13.getLayoutParams().height = y/8;Button button14 = (Button)findViewById(R.id.button14); button14.getLayoutParams().width = x/4 ;button14.getLayoutParams().height = y/8;Button button15 = (Button)findViewById(R.id.button15); button15.getLayoutParams().width = x/4 ;button15.getLayoutParams().height = y/8;Button button16 = (Button)findViewById(R.id.button16); button16.getLayoutParams().width = x/4 ;button16.getLayoutParams().height = y/8;Button button17 = (Button)findViewById(R.id.button17); button17.getLayoutParams().width = x/4 ;button17.getLayoutParams().height = y/8;Button button18 = (Button)findViewById(R.id.button18); button18.getLayoutParams().width = x/4 ;button18.getLayoutParams().height = y/8;Button button19 = (Button)findViewById(R.id.button19); button19.getLayoutParams().width = x/4 ;button19.getLayoutParams().height = y/8;Button button20 = (Button)findViewById(R.id.button20); button20.getLayoutParams().width = x/4 ;button20.getLayoutParams().height = 2*(y/8); Button button21 = (Button)findViewById(R.id.button21); button21.getLayoutParams().width = x/4 ;button21.getLayoutParams().height = y/8;Button button22 = (Button)findViewById(R.id.button22); button22.getLayoutParams().width = x/4 ;button22.getLayoutParams().height = y/8;Button button23 = (Button)findViewById(R.id.button23); button23.getLayoutParams().width = x/4 ;button23.getLayoutParams().height = y/8;button6.setOnClickListener(onEXPListener);button7.setOnClickListener(onEXPListener);button9.setOnClickListener(onEXPListener);button10.setOnClickListener(onEXPListener);button11.setOnClickListener(onEXPListener);button12.setOnClickListener(onEXPListener);button13.setOnClickListener(onEXPListener);button14.setOnClickListener(onEXPListener);button15.setOnClickListener(onEXPListener);button16.setOnClickListener(onEXPListener);button17.setOnClickListener(onEXPListener);button18.setOnClickListener(onEXPListener);button19.setOnClickListener(onEXPListener);button21.setOnClickListener(onEXPListener);button22.setOnClickListener(onEXPListener);button23.setOnClickListener(onEXPListener);button5.setOnClickListener(onClearListener);button8.setOnClickListener(onClearLastListener);button20.setOnClickListener(onEXECListener);button21.setOnClickListener(onPERCENTCListener);}}/*** 初始化所有的组件*/private void InitWigdet() {//获取屏幕参数Display defaultDisplay = getWindowManager().getDefaultDisplay();Point point = new Point();defaultDisplay.getSize(point);Integer x = point.x;Integer y = point.y - 60;// 获取界⾯元素input = (EditText) findViewById(R.id.input);input.setKeyListener(new KeyListener() {@Overridepublic int getInputType() {return 0;}。

麦子学院Android开发教程之开发计算器实例

麦子学院Android开发教程之开发计算器实例

学完了Java(虽说没怎么练手),开始学Android编程。

首先还是做个计算器(感觉这辈子只能做计算器了话说Android的布局真是太方便了,下面是布局文件.例子代码如下:<LinearLayout xmlns:android="/apk/res/android"android:id="@+id/warpcontent"android:layout_width="fill_parent"android:layout_height="fill_parent"android:orientation="vertical" ><HorizontalScrollViewandroid:id="@+id/scrollview"android:layout_width="fill_parent"android:layout_height="wrap_content"><TextViewandroid:id="@+id/resultText"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_gravity="right"android:gravity="right"android:padding="8dp"android:paddingLeft="10dp"android:paddingRight="10dp"android:text="@string/number0"android:textSize="40sp" /></HorizontalScrollView ><TableLayoutandroid:id="@+id/buttonTable"android:layout_width="fill_parent"android:layout_height="0dp"android:layout_weight="1"android:stretchColumns="*" ><TableRowandroid:layout_width="fill_parent"android:layout_height="0dp"android:layout_weight="1" ><Buttonandroid:id="@+id/button7"android:layout_width="wrap_content" android:layout_height="fill_parent" android:onClick="onClickListener"android:text="@string/number7" /> <Buttonandroid:id="@+id/button8"android:layout_width="wrap_content" android:layout_height="fill_parent" android:onClick="onClickListener"android:text="@string/number8" /> <Buttonandroid:id="@+id/button9"android:layout_width="wrap_content" android:layout_height="fill_parent" android:onClick="onClickListener"android:text="@string/number9" /> <Buttonandroid:id="@+id/buttonBackSpace" android:layout_width="wrap_content" android:layout_height="fill_parent" android:onClick="onClickListener"android:text="@string/backspace" /> <Buttonandroid:id="@+id/buttonClear"android:layout_width="wrap_content" android:layout_height="fill_parent" android:onClick="onClickListener"android:text="@string/clear" /></TableRow><TableRowandroid:layout_width="fill_parent"android:layout_height="0dp"android:layout_weight="1" ><Buttonandroid:id="@+id/button4"android:layout_width="wrap_content" android:layout_height="fill_parent" android:onClick="onClickListener"android:text="@string/number4" /> <Buttonandroid:id="@+id/button5"android:layout_width="wrap_content" android:layout_height="fill_parent" android:onClick="onClickListener"android:text="@string/number5" /> <Buttonandroid:id="@+id/button6"android:layout_width="wrap_content" android:layout_height="fill_parent" android:onClick="onClickListener"android:text="@string/number6" /><Buttonandroid:id="@+id/buttonMultiply"android:layout_width="wrap_content" android:layout_height="fill_parent" android:onClick="onClickListener"android:text="@string/multiply" /> <Buttonandroid:id="@+id/buttonDivide"android:layout_width="wrap_content" android:layout_height="fill_parent" android:onClick="onClickListener"android:text="@string/divide" /></TableRow></TableLayout><LinearLayoutandroid:layout_width="fill_parent"android:layout_height="0dp"android:layout_weight="1"android:orientation="horizontal" ><TableLayoutandroid:layout_width="0dp"android:layout_height="fill_parent"android:layout_weight="3"android:stretchColumns="*" ><TableRowandroid:layout_width="fill_parent"android:layout_height="0dp"android:layout_weight="1" ><Buttonandroid:id="@+id/button1"android:layout_height="fill_parent" android:onClick="onClickListener"android:text="@string/number1" /> <Buttonandroid:id="@+id/button2"android:layout_width="wrap_content" android:layout_height="fill_parent" android:onClick="onClickListener"android:text="@string/number2" /> <Buttonandroid:id="@+id/button3"android:layout_width="wrap_content" android:layout_height="fill_parent" android:onClick="onClickListener"android:text="@string/number3" /> </TableRow><TableRowandroid:layout_width="fill_parent"android:layout_height="0dp"android:layout_weight="1" ><Buttonandroid:id="@+id/button0"android:layout_width="wrap_content" android:layout_height="fill_parent" android:onClick="onClickListener"android:text="@string/number0" /> <Buttonandroid:id="@+id/buttonDot"android:layout_width="wrap_content"android:onClick="onClickListener"android:text="@string/dot" /><Buttonandroid:id="@+id/buttonNegSign"android:layout_width="wrap_content" android:layout_height="fill_parent" android:onClick="onClickListener"android:text="@string/negSign" /> </TableRow></TableLayout><Buttonandroid:id="@+id/buttonPlus"android:layout_width="0dp"android:layout_height="fill_parent"android:layout_weight="1"android:onClick="onClickListener"android:text="@string/plus" /><LinearLayoutandroid:layout_width="0dp"android:layout_height="fill_parent"android:layout_weight="1"android:orientation="vertical" ><Buttonandroid:id="@+id/buttonMinus"android:layout_width="fill_parent"android:layout_height="0dp"android:layout_weight="1"android:onClick="onClickListener"android:text="@string/minus"/><Buttonandroid:id="@+id/buttonEval"android:layout_width="fill_parent"android:layout_height="0dp"android:layout_weight="1"android:onClick="onClickListener"android:text="@string/eval" /></LinearLayout></LinearLayout></LinearLayout>MainActivity类和之前的java计算器差不多:代码如下package me.jerrys.calc;import java.math.BigDecimal;import android.support.v7.app.ActionBarActivity; import android.app.AlertDialog;import android.os.Bundle;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.widget.TextView;import android.widget.Toast;public class MainActivity extends ActionBarActivity {private TextView textView;private BigDecimal lastNum = new BigDecimal("0");private BigDecimal currentNum = new BigDecimal("0"); private String currentText;private boolean typeClean = false;private boolean hadCalced = false;private MODE currentMode = MODE.PLUS;private enum MODE {PLUS, MINUS, MULTIPLY, DIVIDE}@Overrideprotected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);setContentView(yout.activity_main);textView = (TextView) findViewById(R.id.resultText); }@Overridepublic boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu);return true;}public void onClickListener(View v) {currentText = textView.getText().toString();switch (v.getId()) {case R.id.button0:addNumber("0");break;case R.id.button1:addNumber("1");break;case R.id.button2:addNumber("2");break;case R.id.button3:addNumber("3");case R.id.button4:addNumber("4");break;case R.id.button5:addNumber("5");break;case R.id.button6:addNumber("6");break;case R.id.button7:addNumber("7");break;case R.id.button8:addNumber("8");break;case R.id.button9:addNumber("9");break;case R.id.buttonNegSign: addSign();break;case R.id.buttonClear:clear();break;case R.id.buttonBackSpace: backSpace();break;case R.id.buttonPlus:setMode(MODE.PLUS);case R.id.buttonMinus:setMode(MODE.MINUS);break;case R.id.buttonMultiply:setMode(MODE.MULTIPLY);break;case R.id.buttonDivide:setMode(MODE.DIVIDE);break;case R.id.buttonEval:calc();break;case R.id.buttonDot:addNumber(".");break;}}private void calc() {if (hadCalced && typeClean) return;currentNum = new BigDecimal(currentText); try {switch (currentMode) {case PLUS:lastNum = lastNum.add(currentNum);break;case MINUS:lastNum = lastNum.subtract(currentNum); break;case MULTIPLY:lastNum = lastNum.multiply(currentNum);break;case DIVIDE:lastNum = lastNum.divide(currentNum, 16,BigDecimal.ROUND_HALF_DOWN);break;}} catch (Exception e) {Toast.makeText(getApplicationContext(), "发生错误:"+e.getMessage(), Toast.LENGTH_SHORT).show();return;}String resultText = lastNum.toString();if (resultText.indexOf(".") > 0) { // 消除小数多余位数resultText = resultText.replaceAll("0+?$", "");resultText = resultText.replaceAll("[.]$", "");}setResultText(resultText);typeClean = true;hadCalced = false;}private void setMode(MODE mode) {if (!hadCalced && !typeClean) {calc();currentMode = mode;return;}lastNum = new BigDecimal(currentText);currentMode = mode;typeClean = true;hadCalced = true;}private void addSign() {if (currentText.equals("0") || currentText.equals("")) return;if (currentText.startsWith("-")) setResultText(currentText.substring(1)); else setResultText("-" + currentText);}private void clear() {currentNum = new BigDecimal("0");lastNum = new BigDecimal("0");typeClean = false;currentMode = MODE.PLUS;setResultText("0");}private void setResultText(String string) {textView.setText(string);}public void addNumber(String num) {String resultText = currentText;if (typeClean == true) {resultText = "0";typeClean = false;}if (num.equals(".") && stIndexOf(".") != -1) return;if ((resultText.equals("0") || resultText.equals(""))&& !num.equals("."))resultText = "";resultText = resultText + num;setResultText(resultText);}private void backSpace() {if (currentText.equals("0") || currentText.equals("")) return;if (currentText.length() == 1) {setResultText("0");return;}setResultText(currentText.substring(0, currentText.length() - 1));}@Override<LinearLayout xmlns:android=" "public boolean onOptionsItemSelected(MenuItem item) {if (item.getItemId() == R.id.action_about) {new AlertDialog.Builder(this).setTitle("关于").setMessage("/android-simple-calc").setPositiveButton("确定", null).show();return true;}return super.onOptionsItemSelected(item);}}。

androidstudio实现简单的计算器功能

androidstudio实现简单的计算器功能

androidstudio实现简单的计算器功能本⽂实例为⼤家分享了android studio实现计算器的具体代码,供⼤家参考,具体内容如下先来个效果图:功能:满⾜加减乘除四则运算规则,有回退、清除功能。

下⾯的代码只是完成基本功能,若添加背景图先看看下⾯的⽅法:Android Studio App设置背景图⽚1、本地准备好图⽚,复制它,粘贴进mipmap(drawable)⽂件夹。

2、在activity_main.xml⾥添加下⾯代码,注意添加位置。

3、完成,效果图:content_main.xml⽂件(页⾯布局,content_main.xml代码包含在activity_main.xml⽂件中):<?xml version="1.0" encoding="utf-8"?><android.support.constraint.ConstraintLayout xmlns:android="/apk/res/android"xmlns:app="/apk/res-auto"xmlns:tools="/tools"android:id="@+id/next"android:layout_width="match_parent"android:layout_height="match_parent"app:layout_behavior="@string/appbar_scrolling_view_behavior"tools:context=".MainActivity"tools:showIn="@layout/activity_main"><!--<TextView--><!--android:layout_width="wrap_content"--><!--android:layout_height="wrap_content"--><!--android:text="Hello World!"--><!--app:layout_constraintBottom_toBottomOf="parent"--><!--app:layout_constraintLeft_toLeftOf="parent"--><!--app:layout_constraintRight_toRightOf="parent"--><!--app:layout_constraintTop_toTopOf="parent" />--><LinearLayoutandroid:layout_width="fill_parent"android:layout_height="match_parent"android:orientation="vertical" ><EditTextandroid:id="@+id/input"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_gravity="center"android:editable="false"android:hint="@string/shuru" /><EditTextandroid:id="@+id/output"android:layout_width="match_parent"android:layout_height="70dp"android:layout_gravity="center"android:editable="true"android:gravity="right"android:hint="@string/shuchu" /><RelativeLayoutandroid:layout_width="350dp"android:layout_height="wrap_content"android:layout_gravity="center"><Buttonandroid:id="@+id/clear"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignParentLeft="true"android:text="@string/clear"android:textSize="40sp" /><Buttonandroid:id="@+id/back"android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_toRightOf="@id/clear" android:text="@string/back"android:textSize="40sp" /><Buttonandroid:id="@+id/divide"android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_toRightOf="@id/back" android:text="@string/divide"android:textSize="40sp" /><Buttonandroid:id="@+id/multiply"android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_toRightOf="@id/divide" android:text="@string/multiply"android:textSize="40sp" /><Buttonandroid:id="@+id/seven"android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_below="@id/clear"android:text="@string/seven"android:textSize="40sp" /><Buttonandroid:id="@+id/eight"android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_toRightOf="@id/seven" android:layout_below="@id/divide"android:text="@string/eight"android:textSize="40sp" /><Buttonandroid:id="@+id/nine"android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/multiply" android:layout_toRightOf="@id/eight" android:text="@string/nine"android:textSize="40sp" /><Buttonandroid:id="@+id/subtract"android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_below="@id/multiply" android:layout_toRightOf="@id/nine" android:text="@string/subtract"android:textSize="40sp" /><Buttonandroid:id="@+id/four"android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_below="@id/seven"android:text="@string/four"android:textSize="40sp" /><Buttonandroid:id="@+id/five"android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/eight"android:layout_toRightOf="@id/four" android:text="@string/five"android:textSize="40sp" /><Buttonandroid:id="@+id/six"android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/nine"android:layout_toRightOf="@id/five" android:text="@string/six"android:textSize="40sp" /><Buttonandroid:id="@+id/add"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignParentRight="true"android:layout_below="@id/subtract"android:layout_toRightOf="@id/six"android:text="@string/add"android:textSize="40sp" /><Buttonandroid:id="@+id/one"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignParentLeft="true"android:layout_below="@id/four"android:text="@string/one"android:textSize="40sp" /><Buttonandroid:id="@+id/two"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_below="@id/five"android:layout_toRightOf="@id/one"android:text="@string/two"android:textSize="40sp" /><Buttonandroid:id="@+id/three"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_below="@id/six"android:layout_toRightOf="@id/two"android:text="@string/three"android:textSize="40sp" /><Buttonandroid:id="@+id/result"android:layout_width="wrap_content"android:layout_height="146dp"android:layout_alignParentRight="true"android:layout_below="@id/add"android:layout_toRightOf="@id/three"android:text="@string/result"android:textSize="40sp" /><Buttonandroid:id="@+id/zero"android:layout_width="175dp"android:layout_height="wrap_content"android:layout_alignParentLeft="true"android:layout_below="@id/one"android:text="@string/zero"android:textSize="40sp" /><Buttonandroid:id="@+id/dot"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_below="@id/three"android:layout_toRightOf="@id/zero"android:text="@string/dot"android:textSize="40sp" /></RelativeLayout></LinearLayout></android.support.constraint.ConstraintLayout>strings.xml(content_main.xml代码中的⼀些变量在此代码中定义的):<resources><string name="app_name">Calculator</string><string name="action_settings">Settings</string><string name="title_activity_page2">page2</string><string name="next">下⼀页</string><string name="zero">0</string><string name="one">1</string><string name="two">2</string><string name="three">3</string><string name="four">4</string><string name="five">5</string><string name="six">6</string><string name="seven">7</string><string name="eight">8</string><string name="nine">9</string><string name="add">+</string><string name="subtract">-</string><string name="multiply">*</string><string name="divide">/</string><string name="clear">CE</string><string name="back">&#60;-</string><string name="result">=</string><string name="shuru">请输⼊:</string><string name="shuchu">结果:</string><string name="dot">.</string><string name="resultText">计算式</string></resources>MainActivity.Java(计算器中实现计算功能的核⼼代码):package com.example.dell.calculator;import android.content.Intent;import android.os.Bundle;import android.support.design.widget.FloatingActionButton;import android.support.design.widget.Snackbar;import android.support.v7.app.AppCompatActivity;import android.support.v7.widget.Toolbar;import android.view.View;import android.view.Menu;import android.view.MenuItem;import android.app.Activity;import android.content.Context;import android.view.View.OnClickListener;import android.widget.CheckBox;import android.widget.EditText;import android.widget.Button;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.text.DecimalFormat;import java.text.NumberFormat;import java.util.regex.Matcher;import java.util.regex.Pattern;public class MainActivity extends AppCompatActivity {private EditText output = null;private EditText input = null;private Button btn0 = null;private Button btn1 = null;private Button btn2 = null;private Button btn3 = null;private Button btn4 = null;private Button btn5 = null;private Button btn6 = null;private Button btn7 = null;private Button btn8 = null;private Button btn9 = null;private Button btnadd = null;private Button btnsubtract = null;private Button btnmultiply = null;private Button btndivide = null;private Button btnclear = null;private Button btnback = null;private Button btndot = null;private Button btnresult = null;private String text = "";//保存输⼊的数字和符号private Double result = 0.0;//输出结果@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(yout.activity_main);Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);setSupportActionBar(toolbar);output = (EditText) findViewById(R.id.output);input = (EditText) findViewById(R.id.input);btn0 = (Button) findViewById(R.id.zero);btn1 = (Button) findViewById(R.id.one);btn2 = (Button) findViewById(R.id.two);btn3 = (Button) findViewById(R.id.three);btn4 = (Button) findViewById(R.id.four);btn5 = (Button) findViewById(R.id.five);btn6 = (Button) findViewById(R.id.six);btn7 = (Button) findViewById(R.id.seven);btn8 = (Button) findViewById(R.id.eight);btn9 = (Button) findViewById(R.id.nine);btnadd = (Button) findViewById(R.id.add);btnsubtract = (Button) findViewById(R.id.subtract);btnmultiply = (Button) findViewById(R.id.multiply);btndivide = (Button) findViewById(R.id.divide);btnclear = (Button) findViewById(R.id.clear);btnback = (Button) findViewById(R.id.back);btndot = (Button) findViewById(R.id.dot);btnresult = (Button) findViewById(R.id.result);//设置按钮侦听事件btn0.setOnClickListener(listener);btn1.setOnClickListener(listener);btn2.setOnClickListener(listener);btn3.setOnClickListener(listener);btn4.setOnClickListener(listener);btn5.setOnClickListener(listener);btn6.setOnClickListener(listener);btn7.setOnClickListener(listener);btn8.setOnClickListener(listener);btn9.setOnClickListener(listener);btnadd.setOnClickListener(listener);btnsubtract.setOnClickListener(listener);btnmultiply.setOnClickListener(listener);btndivide.setOnClickListener(listener);btnclear.setOnClickListener(listener);btnback.setOnClickListener(listener);btndot.setOnClickListener(listener);btnresult.setOnClickListener(listener);FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);fab.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) .setAction("Action", null).show();}});}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {// Inflate the menu; this adds items to the action bar if it is present.getMenuInflater().inflate(R.menu.menu_main, menu);return true;}@Overridepublic boolean onOptionsItemSelected(MenuItem item) {// Handle action bar item clicks here. The action bar will// automatically handle clicks on the Home/Up button, so long// as you specify a parent activity in AndroidManifest.xml.int id = item.getItemId();//noinspection SimplifiableIfStatementif (id == R.id.action_settings) {return true;}return super.onOptionsItemSelected(item);}//public void onClickNext(View view) {// Intent intent = new Intent(this,page2.class);// startActivity(intent);// }private OnClickListener listener = new OnClickListener() {public void onClick(View v) {// TODO Auto-generated method stubswitch (v.getId()) {//输⼊数字case R.id.zero:num(0);break;case R.id.one:num(1);break;case R.id.two:num(2);break;case R.id.three:num(3);break;case R.id.four:num(4);break;case R.id.five:num(5);break;case R.id.six:num(6);break;case R.id.seven:num(7);break;case R.id.eight:num(8);break;case R.id.nine:num(9);break;case R.id.dot:dot();break;//执⾏运算case R.id.add:add();break;case R.id.subtract:sub();break;case R.id.multiply:multiply();break;case R.id.divide:divide();break;case R.id.clear:clear();break;case R.id.back:back();break;//计算结果case R.id.result:result();break;default:break;}input.setText(text);output.setText(String.valueOf(result)); }};private void num(int i) {// TODO Auto-generated method stubtext = text + String.valueOf(i);}private void dot() {// TODO Auto-generated method stubtext = text + ".";}private void clear() {// TODO Auto-generated method stubtext = "";result = null;input.setText("");output.setText("");}private void back() {// TODO Auto-generated method stubString str = text.substring(0, text.length()-1); text = str;}private void add() {// TODO Auto-generated method stubtext += "+";}private void sub() {// TODO Auto-generated method stubtext += "-";}private void multiply() {// TODO Auto-generated method stubtext += "*";}private void divide() {// TODO Auto-generated method stubtext += "/";}//计算输出结果private void result() {// TODO Auto-generated method stubresult = testOperation(text);}public Double testOperation(String s){//分割字符然后放进数组String s1 =s.replace("+","-");String[] str = s1.split("-");double total1=0;//先遍历数组,把⾥⾯的乘除结果算出来for(String str1:str){if(str1.contains("*")||str1.contains("/")){double total = 0;for(int i =0;i<str1.length();){int count =1;a:for(int j =i+1;j<str1.length();j++){char c =str1.charAt(j);if(c=='*'||c=='/'){break a;}else{count++;}}//将数字截取出来String s2 =str1.substring(i,i+count);double d = Double.parseDouble(s2);if(i==0){total = d;}else{char c1 = str1.charAt(i-1);if(c1=='*'){total*=d;}else if(c1=='/'){//如果除数为0,直接返回null;if(d == 0)return null;total/=d;}}i+=count+1;}s= s.replace(str1, total+"");}}//进⾏加减运算for(int i =0;i<s.length();i++){int count =1;a:for(int j=i+1;j<s.length();j++){char c = s.charAt(j);if(c=='+'||c=='-'){break a;}else{count++;}}String s3= s.substring(i,i+count);double d2 = Double.parseDouble(s3);if(i==0){total1 = d2;}else{char c = s.charAt(i-1);if(c=='+'){total1+=d2;}else if(c=='-'){total1-=d2;}}i+=count;}return total1;}}更多计算器功能实现,请点击专题:进⾏学习关于Android计算器功能的实现,查看专题:进⾏学习。

自己写的计算器(加减乘除)代码

自己写的计算器(加减乘除)代码

⾃⼰写的计算器(加减乘除)代码⾸先是Calculator计算器类package zydCalr;public class Calculator {public double addition(double number1, double number2) {return number1+number2;}public double subtraction(double number1, double number2) {return number1-number2;}public double multiplication(double number1, double number2) {return number1*number2;}public double divsition(double number1, double number2) {return number1/number2;}}接下来是Execute运⾏类package zydCalr;import java.util.Scanner;public class Execution {public double execute(String str){String expression = str + "+1";// 初始化开始//char[] Cexpression = expression.toCharArray();// 创建运算器Calculator calculator = new Calculator();// 数值列表double[] numbers = new double[30];int numbersindex = 0;// 转型列表char[] sub = new char[30];// 数值下标位置int count = 0;// 符号列表char[] symbols = new char[10];int symbolsindex = 0;// temp1是数值列表上⼀个数值,temp2是当前的数值double temp1 = 0, temp2 = 0;;// 符号char symbol = 0;int flag = 1;// 初始化结束// 第⼀次遍历for (int i = 0; i < expression.length(); i++) {if (Cexpression[i] >= '0' && sub[i] <= '9') {sub[count++] = Cexpression[i];} else {// 字符串转型doubletemp2 = transition(sub,count);// 当flag=2时进⾏运算if (flag == 2) {flag = 1;// 获取数值列表前⼀个数值;temp1 = numbers[numbersindex - 1];// 判断symbol乘法还是除法,成功是乘法,失败为除法if (decide(symbol)==1) {temp2 = calculator.multiplication(temp1, temp2);} else {temp2 = calculator.divsition(temp1, temp2);}// 覆盖前⼀个数值numbersindex--;}// temp2存⼊数值列表numbers[numbersindex++] = temp2;// 获取符号symbol = Cexpression[i];// 转型数值下标位置清零count = 0;// 判断是否⼤于flag,flag=2,不⼤于则加⼊到符号列表if (judge(symbol) > flag) {flag = 2;} else {// 加⼊到符号列表symbols[symbolsindex++] = symbol;}}}double temp = numbers[0];count = 0;for (int i = 1; i < numbers.length; i++) {if (symbols[count] == '+') {temp += numbers[i];count++;} else if (symbols[count] == '-') {temp -= numbers[i];count++;}}return temp;}private static int judge(char symbol) {if (symbol == '+') {return 1;} else if (symbol == '-') {return 1;} else if (symbol == '*') {return 2;} else if (symbol == '/') {return 2;}return 0;}private static int decide(char symbol) {if (symbol == '*') {return 1;} else if (symbol == '/') {return 2;}return 2;}private static int transition(char[] sub1,int count) {int temp = 0;for (int i = 0; i < count; i++) {if (sub1[i] >= '0' && sub1[i] <= '9') {temp = temp * 10;temp += (sub1[i] - '0');}}return temp;}}产⽣表达式类package zydCalr;import java.util.Random;public class ProductionExpression {//⽣成数值public static String producerNumber() {int number = (int) (Math.random() * 50);return String.valueOf(number);}//⽣成数值public static String producerOpreator() {int number = (int) (Math.random() * 4);String[] operator = { "+", "-", "*", "/" };return operator[number];}//产⽣public static String producer(int i) {StringBuilder sb = new StringBuilder();int flag = (int) (Math.random() * 5);if(flag==1){sb.append("-");}sb.append(producerNumber());while (i > 0) {sb.append(producerOpreator());sb.append(producerNumber());i--;}return sb.toString();}//产⽣表达式public static String producerExpression() {int lenght = (int) (Math.random() * 5);if (lenght % 2 == 0) {lenght++;}String expression = producer(lenght);return expression;}}⽣产者类package zydCalr;import java.util.ArrayList;import java.util.List;public class Producer implements Runnable {static final int MAXQUEUE = 5;private List<String> messages = new ArrayList<String>(); private ProductionExpression pe=new ProductionExpression(); @Overridepublic void run() {// TODO Auto-generated method stubwhile (true) {putMessage();try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}}}private synchronized void putMessage() {while (messages.size() >= MAXQUEUE) {try {wait();} catch (InterruptedException e) {e.printStackTrace();}}//⽣成表达式messages.add(pe.producerExpression());notify();}public synchronized String getMessage() {while (messages.size() == 0) {try {notify();wait();} catch (InterruptedException e) {e.printStackTrace();}}String message = (String) messages.remove(0);notify();return message;}}消费者类package zydCalr;public class Consumer implements Runnable {Producer producer;Consumer(Producer producer) {this.producer = producer;}public void run() {while (true) {System.out.println("-------------开始⼀组表达式处理-------------");String message = producer.getMessage();System.out.println("⽣成表达式:" + message);Execution exe=new Execution();System.out.printf("处理结果:"+"%.2f\n",exe.execute(message));try {Thread.sleep(2000);} catch (InterruptedException e) {e.printStackTrace();}}}public static void main(String[] args) {Producer producer = new Producer();new Thread(producer).start();Consumer consumer = new Consumer(producer);new Thread(consumer).start();}}代码还是很简单的,主要有两个列表,⼀个列表存数值,⼀个列表存符号,如果符号是乘法或者除法,则把当前的数值和数值列表最后的数值相乘或相除,然后覆盖到数字列表的最后,如果不是,则存⼊数值列表的最后,符号列表添加当前的减法或者乘法,最后我发现许多细节的东西没有处理。

iOS纯代码实现一个计算器(只有加法)

iOS纯代码实现一个计算器(只有加法)

iOS纯代码实现⼀个计算器(只有加法)#import "ViewController.h"@interface ViewController ()@property (nonatomic,weak) UITextField *num1Text;@property (nonatomic,weak) UITextField *num2Text;@property (nonatomic,weak) UILabel *resultLabel;@end@implementation ViewController- (void)viewDidLoad {[super viewDidLoad];// Do any additional setup after loading the view, typically from a nib.//调⽤界⾯设置⽅法[self setupUI];}//设置界⾯⽅法#pragma mark -设置界⾯- (void)setupUI{//设置视图背景颜⾊self.view.backgroundColor=[UIColor blackColor];//实例化两个⽂本框UITextField *num1Text=[[UITextField alloc] initWithFrame:CGRectMake(20, 40, 100, 40)];UITextField *num2Text=[[UITextField alloc] initWithFrame:CGRectMake(150, 40, 100, 40)];//设置两个⽂本框的背景颜⾊num1Text.backgroundColor=[UIColor whiteColor];num2Text.backgroundColor=[UIColor whiteColor];//将两个⽂本框添加到根视图[self.view addSubview:num1Text];[self.view addSubview:num2Text];//将两个⽂本框对象赋值给属性_num1Text=num1Text;_num2Text=num2Text;//实例化三个Label对象UILabel *plusLabel=[[UILabel alloc] initWithFrame:CGRectMake(130, 40, 40, 40)]; UILabel *equalLabel=[[UILabel alloc] initWithFrame:CGRectMake(260, 40, 40, 40)]; UILabel *resultLabel=[[UILabel alloc] initWithFrame:CGRectMake(310, 40, 40, 40)];//给Label对象设置⽂本plusLabel.text=@"+";equalLabel.text=@"=";resultLabel.text=@"result";//给Label对象[plusLabel setTextColor:[UIColor whiteColor]];[equalLabel setTextColor:[UIColor whiteColor]];[resultLabel setTextColor:[UIColor whiteColor]];//设置边框⼤⼩⾃动按内容调整[plusLabel sizeToFit];[equalLabel sizeToFit];[resultLabel sizeToFit];//将label添加到根视图[self.view addSubview:plusLabel];[self.view addSubview:equalLabel];[self.view addSubview:resultLabel];//将计算结果的label赋值给对应属性_resultLabel=resultLabel;//实例化⼀个按钮UIButton *calculate=[[UIButton alloc] initWithFrame:CGRectMake(200, 120, 50, 30)]; //设置按钮的名称和字的颜⾊[calculate setTitle:@"计算" forState:UIControlStateNormal];[calculate setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];//设置按钮的背景颜⾊[calculate setBackgroundColor:[UIColor whiteColor]];//将按钮添加到根视图[self.view addSubview:calculate];//设置⼀个事件[calculate addTarget:self action:@selector(add) forControlEvents:UIControlEventTouchUpInside]; }//计算⽅法- (void)add{//获取两个⽂本框的内容并转换为整型NSInteger num1=[_num1Text.text intValue];NSInteger num2=[_num2Text.text intValue ];NSInteger result=num1+num2;//将result封装成⼀个NSNumber类型的对象,调⽤它的description⽅法获得字符串赋值给结果Label _resultLabel.text=@(result).description;}@end。

程序员计算器APP的程序设计及代码示例

程序员计算器APP的程序设计及代码示例

程序员计算器APP的程序设计及代码示例随着科技的不断发展,计算器作为一种必备工具,已经成为现代生活中不可或缺的一部分。

针对程序员这个特殊群体的需求,开发一款适用于程序员的计算器APP就变得非常重要。

本文将要探讨程序员计算器APP的程序设计和提供一些代码示例。

**1. 设计思路**在设计程序员计算器APP时,需要考虑到程序员的特殊需求,如二进制、八进制和十六进制数值的转换,位运算,还要具备基本的四则运算功能。

为了满足这些需求,我们可以采用面向对象的编程方式,将不同功能拆分成多个类,并通过类的继承和组合实现不同功能的组合。

**2. 基本功能**程序员计算器APP的基本功能包括:- 十进制到二进制、八进制和十六进制的转换- 二进制、八进制和十六进制到十进制的转换- 位运算(与、或、异或、取反)- 四则运算(加、减、乘、除)**3. 类的设计**根据上述需求,我们可以设计以下几个类:**3.1 计算器类(Calculator)**```pythonclass Calculator:def __init__(self):# 初始化def decimal_to_binary(self, num): # 十进制转二进制的方法def decimal_to_octal(self, num):# 十进制转八进制的方法def decimal_to_hex(self, num):# 十进制转十六进制的方法def binary_to_decimal(self, num): # 二进制转十进制的方法def octal_to_decimal(self, num):# 八进制转十进制的方法def hex_to_decimal(self, num):# 十六进制转十进制的方法def bitwise_and(self, num1, num2):# 位与运算的方法def bitwise_or(self, num1, num2):# 位或运算的方法def bitwise_xor(self, num1, num2):# 位异或运算的方法def bitwise_not(self, num):# 位取反运算的方法def add(self, num1, num2):# 加法运算的方法def subtract(self, num1, num2):# 减法运算的方法def multiply(self, num1, num2):# 乘法运算的方法def divide(self, num1, num2):# 除法运算的方法```**3.2 二进制转换类(BinaryConverter)** ```pythonclass BinaryConverter:def __init__(self):# 初始化def decimal_to_binary(self, num):# 十进制转二进制的方法def binary_to_decimal(self, num):# 二进制转十进制的方法```**3.3 八进制转换类(OctalConverter)** ```pythonclass OctalConverter:def __init__(self):# 初始化def decimal_to_octal(self, num):# 十进制转八进制的方法def octal_to_decimal(self, num):# 八进制转十进制的方法```**3.4 十六进制转换类(HexConverter)** ```pythonclass HexConverter:def __init__(self):# 初始化def decimal_to_hex(self, num):# 十进制转十六进制的方法def hex_to_decimal(self, num):# 十六进制转十进制的方法```**3.5 位运算类(BitwiseCalculator)**```pythonclass BitwiseCalculator:def __init__(self):# 初始化def bitwise_and(self, num1, num2):# 位与运算的方法def bitwise_or(self, num1, num2):def bitwise_xor(self, num1, num2):# 位异或运算的方法def bitwise_not(self, num):# 位取反运算的方法```**3.6 四则运算类(ArithmeticCalculator)** ```pythonclass ArithmeticCalculator:def __init__(self):# 初始化def add(self, num1, num2):# 加法运算的方法def subtract(self, num1, num2):# 减法运算的方法def multiply(self, num1, num2):# 乘法运算的方法def divide(self, num1, num2):```**4. 代码示例**以下是一个简单的代码示例,用于演示程序员计算器APP的基本功能:```pythoncalculator = Calculator()# 十进制转二进制示例dec_to_bin = calculator.decimal_to_binary(10)print(dec_to_bin) # 输出:1010# 二进制转十进制示例bin_to_dec = calculator.binary_to_decimal(1010)print(bin_to_dec) # 输出:10# 位与运算示例bitwise_and = calculator.bitwise_and(5, 3)print(bitwise_and) # 输出:1# 加法运算示例addition = calculator.add(5, 3)print(addition) # 输出:8```通过以上代码示例,我们可以看到程序员计算器APP的基本功能已经实现。

Android实现简易计算器小程序

Android实现简易计算器小程序

Android实现简易计算器⼩程序本⽂实例为⼤家分享了Android实现简易计算器⼩程序的具体代码,供⼤家参考,具体内容如下⽬标效果:通过编写代码,可以实现整数和⼩数的加减乘除运算,以及删除和清空的功能。

1.页⾯中Button使⽤的是线性布局,最外边⼀个是⽗布局,第⼀⾏C,DEL,/,*为第⼀个⼦布局,第⼆⾏7,8,9,-为第⼆个⼦布局,第三⾏4,5,6,+为第三个⼦布局,第四五⾏为第四个⼦布局,第四个⼦布局中还有两个相当于是孙布局的级别,1,2,3为第⼀个孙布局,0和.为第⼆个孙布局,=在两个孙布局之外第四个⼦布局以内。

因为计算器的⽔平竖直排列⼗分鲜明,所以可以⽤线性布局,当然也可以⽤表格布局来进⾏排布。

2.activity_main.xml页⾯⽤于存放所有控件。

activity_main.xml页⾯:<LinearLayout xmlns:android="/apk/res/android"android:layout_width="fill_parent"android:layout_marginTop="40dp"android:layout_height="fill_parent"android:orientation="vertical" ><EditTextandroid:id="@+id/etInput"android:layout_width="310dp"android:layout_height="60dip"android:editable="false" //代表不能进⾏键盘输⼊android:gravity="right" //⽂字靠右边android:layout_gravity="center"android:background="@drawable/white_bg"/> <!-- 设置输⼊框的背景,为⼀个xml⽂件 --><LinearLayoutandroid:layout_width="fill_parent"android:layout_height="wrap_content"android:layout_marginTop="5dp"android:gravity="center_horizontal"android:orientation="horizontal" > <!-- 代表⽔平排布 --><Buttonandroid:id="@+id/btClear"android:background="@drawable/white_select" //设置按钮的背景,为⼀个xml⽂件android:layout_width="75dp"android:layout_height="60dp"android:textSize="20sp"android:text="C" /><Buttonandroid:textSize="20sp"android:text="DEL" /><Buttonandroid:id="@+id/btDivide"android:background="@drawable/white_select" android:layout_marginLeft="5dp"android:layout_width="75dp"android:layout_height="60dp"android:textSize="20sp"android:text="/" /><Buttonandroid:id="@+id/btMul"android:background="@drawable/white_select" android:layout_marginLeft="5dp"android:layout_width="75dp"android:layout_height="60dp"android:textSize="20sp"android:text="*" /></LinearLayout><LinearLayoutandroid:layout_width="fill_parent"android:layout_height="wrap_content"android:layout_marginTop="5dp"android:gravity="center_horizontal"android:orientation="horizontal" ><Buttonandroid:id="@+id/btSeven"android:background="@drawable/white_select" android:layout_width="75dp"android:layout_height="60dp"android:textSize="20sp"android:text="7" /><Buttonandroid:id="@+id/btEight"android:background="@drawable/white_select" android:layout_marginLeft="5dp"android:layout_width="75dp"android:layout_height="60dp"android:textSize="20sp"android:text="8" /><Buttonandroid:id="@+id/btNine"android:background="@drawable/white_select" android:layout_marginLeft="5dp"android:layout_width="75dp"android:layout_height="60dp"android:textSize="20sp"android:text="9" /><Buttonandroid:id="@+id/btJian"android:background="@drawable/white_select" android:layout_marginLeft="5dp"android:layout_width="75dp"android:layout_height="60dp"android:textSize="20sp"android:text="-" /></LinearLayout><LinearLayoutandroid:layout_width="fill_parent"android:layout_height="wrap_content"android:layout_marginTop="5dp"android:gravity="center_horizontal"android:orientation="horizontal" ><Buttonandroid:id="@+id/btFour"android:background="@drawable/white_select" android:layout_width="75dp"android:layout_height="60dp"android:textSize="20sp"android:text="5" /><Buttonandroid:id="@+id/btSix"android:background="@drawable/white_select" android:layout_marginLeft="5dp"android:layout_width="75dp"android:layout_height="60dp"android:textSize="20sp"android:text="6" /><Buttonandroid:id="@+id/btJia"android:background="@drawable/white_select" android:layout_marginLeft="5dp"android:layout_width="75dp"android:layout_height="60dp"android:textSize="20sp"android:text="+" /></LinearLayout><LinearLayoutandroid:layout_width="fill_parent"android:layout_height="wrap_content"android:layout_marginTop="5dp"android:gravity="center_horizontal"android:orientation="horizontal" ><LinearLayoutandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:orientation="vertical" ><LinearLayoutandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:orientation="horizontal" ><Buttonandroid:id="@+id/btOne"android:background="@drawable/white_select" android:layout_width="75dp"android:layout_height="60dp"android:textSize="20sp"android:text="1" /><Buttonandroid:id="@+id/btTwo"android:background="@drawable/white_select" android:layout_marginLeft="5dp"android:layout_width="75dp"android:layout_height="60dp"android:textSize="20sp"android:text="2" /><Buttonandroid:id="@+id/btThree"android:background="@drawable/white_select" android:layout_marginLeft="5dp"android:layout_width="75dp"android:layout_height="60dp"android:textSize="20sp"android:text="3" /></LinearLayout><LinearLayoutandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginTop="5dp"android:orientation="horizontal" ><Buttonandroid:id="@+id/btZero"android:background="@drawable/white_select" android:layout_width="155dp"android:layout_height="60dp"android:textSize="20sp"android:text="." /></LinearLayout></LinearLayout><Buttonandroid:layout_width="75dp"android:background="@drawable/orange_select"android:layout_height="125dp"android:text="="android:layout_marginLeft="5dp"android:textSize="20sp"android:gravity="center"android:id="@+id/btEqu"></Button></LinearLayout></LinearLayout>2.等号按钮和其余按钮的背景及点击效果不同。

Android开发计算器(代码无误,步骤详细)

Android开发计算器(代码无误,步骤详细)

Android开发计算器项目。

功能介绍计算器:计算器拥有加、减、乘、除四个简单的运算。

并有清除功能。

运行界面:界面文件 main.xml<?xml version="1.0"encoding="utf-8"?><LinearLayoutxmlns:android="/apk/res/android"android:orientation="vertical"android:layout_width="fill_parent"android:layout_height="fill_parent"><EditTextandroid:id="@+id/EditText"android:layout_width="fill_parent"android:layout_height="wrap_content"android:digits="1234567890."android:layout_marginBottom="10px"android:gravity="right"/><TableLayoutandroid:orientation="vertical"android:layout_width="fill_parent"android:layout_height="wrap_content"android:gravity="center_horizontal"> <TableRowandroid:layout_marginBottom="5dp"><Buttonandroid:id="@+id/onebut"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginRight="5dp"android:textSize="14pt"android:text="1"android:layout_weight="1"/><Buttonandroid:id="@+id/twobut"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginRight="5dp"android:textSize="14pt"android:text="2"android:layout_weight="1"/><Buttonandroid:id="@+id/threebut"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginRight="5dp"android:textSize="14pt"android:text="3"android:layout_weight="1"/><Buttonandroid:id="@+id/addbut"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginRight="5dp"android:textSize="14pt"android:text="+"android:layout_weight="1"/></TableRow><TableRowandroid:layout_marginBottom="5dp"> <Buttonandroid:id="@+id/fourbut"android:layout_width="wrap_content"android:layout_height="wrap_content"android:textSize="14pt"android:layout_marginRight="5dp"android:text="4"android:layout_weight="1"/><Buttonandroid:id="@+id/fivebut"android:layout_width="wrap_content"android:layout_height="wrap_content"android:textSize="14pt"android:layout_marginRight="5dp"android:text="5"android:layout_weight="1"/><Buttonandroid:id="@+id/sixbut"android:layout_width="wrap_content"android:layout_height="wrap_content"android:textSize="14pt"android:layout_marginRight="5dp"android:text="6"android:layout_weight="1"/><Buttonandroid:id="@+id/subbut"android:layout_width="wrap_content"android:layout_height="wrap_content"android:textSize="14pt"android:layout_marginRight="5dp"android:text="-"android:layout_weight="1"/></TableRow><TableRowandroid:layout_marginBottom="5dp"> <Buttonandroid:id="@+id/sevenbut"android:layout_width="wrap_content"android:layout_height="wrap_content"android:textSize="14pt"android:layout_marginRight="5dp"android:text="7"android:layout_weight="1"/><Buttonandroid:id="@+id/eightbut"android:layout_width="wrap_content"android:layout_height="wrap_content"android:textSize="14pt"android:layout_marginRight="5dp"android:text="8"android:layout_weight="1"/><Buttonandroid:id="@+id/ninebut"android:layout_width="wrap_content"android:layout_height="wrap_content"android:textSize="14pt"android:layout_marginRight="5dp"android:text="9"android:layout_weight="1"/><Buttonandroid:id="@+id/multbut"android:layout_width="wrap_content"android:layout_height="wrap_content"android:textSize="14pt"android:layout_marginRight="5dp"android:text="*"android:layout_weight="1"/></TableRow><TableRowandroid:layout_marginBottom="5dp"><Buttonandroid:id="@+id/zerobut"android:layout_width="wrap_content"android:layout_height="wrap_content"android:textSize="14pt"android:layout_marginRight="5dp"android:text="0"android:layout_weight="1"/><Buttonandroid:id="@+id/dotbut"android:layout_width="wrap_content"android:layout_height="wrap_content"android:textSize="14pt"android:layout_marginRight="5dp"android:text="."android:layout_weight="1"/><Buttonandroid:id="@+id/equalbut"android:layout_width="wrap_content"android:layout_height="wrap_content"android:textSize="14pt"android:layout_marginRight="5dp"android:text="="android:layout_weight="1"/><Buttonandroid:id="@+id/dividebut"android:layout_width="wrap_content"android:layout_height="wrap_content"android:textSize="14pt"android:layout_marginRight="5dp"android:text="/"android:layout_weight="1"/></TableRow></TableLayout><Buttonandroid:id="@+id/clearbut"android:layout_width="fill_parent"android:layout_height="wrap_content"android:text="clear"/></LinearLayout>JAVA文件 Calculator.javapackage com.calculator;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;import android.widget.Toast;public class Calculator extends Activity { /** Called when the activity is first created. */ private EditText edittext;private Button num_zerobut;private Button num_onebut;private Button num_twobut;private Button num_threebut;private Button num_fourbut;private Button num_fivebut;private Button num_sixbut;private Button num_sevenbut;private Button num_eightbut;private Button num_ninebut;private Button dotbut;private Button addbut;private Button subbut;private Button multbut;private Button dividebut;private Button equalbut;private Button clearbut;private String s1=""; //s1,s2存储值private String s2="";private String s3=""; //存储符号private double result;private int flag=0;@Overridepublic void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);setContentView(yout.main);edittext=(EditText)findViewById(R.id.EditText);num_zerobut=(Button)findViewById(R.id.zerobut);num_onebut=(Button)findViewById(R.id.onebut);num_twobut=(Button)findViewById(R.id.twobut);num_threebut=(Button)findViewById(R.id.threebut);num_fourbut=(Button)findViewById(R.id.fourbut);num_fivebut=(Button)findViewById(R.id.fivebut);num_sixbut=(Button)findViewById(R.id.sixbut);num_sevenbut=(Button)findViewById(R.id.sevenbut);num_eightbut=(Button)findViewById(R.id.eightbut);num_ninebut=(Button)findViewById(R.id.ninebut);dotbut=(Button)findViewById(R.id.dotbut);addbut=(Button)findViewById(R.id.addbut);subbut=(Button)findViewById(R.id.subbut);multbut=(Button)findViewById(R.id.multbut);dividebut=(Button)findViewById(R.id.dividebut);equalbut=(Button)findViewById(R.id.equalbut);clearbut=(Button)findViewById(R.id.clearbut);num_zerobut.setOnClickListener(new ButtonListener());num_onebut.setOnClickListener(new ButtonListener());num_twobut.setOnClickListener(new ButtonListener());num_threebut.setOnClickListener(new ButtonListener());num_fourbut.setOnClickListener(new ButtonListener());num_fivebut.setOnClickListener(new ButtonListener());num_sixbut.setOnClickListener(new ButtonListener());num_sevenbut.setOnClickListener(new ButtonListener());num_eightbut.setOnClickListener(new ButtonListener());num_ninebut.setOnClickListener(new ButtonListener());dotbut.setOnClickListener(new ButtonListener());addbut.setOnClickListener(new ButtonListener());subbut.setOnClickListener(new ButtonListener());multbut.setOnClickListener(new ButtonListener());dividebut.setOnClickListener(new ButtonListener());equalbut.setOnClickListener(new ButtonListener());clearbut.setOnClickListener(new ButtonListener());}class ButtonListener implements OnClickListener{public void onClick(View v) {// TODO Auto-generated method stubint i=((Button)v).getId();switch (i) {case R.id.zerobut:s1+=num_zerobut.getText().toString().trim();edittext.setText(s1);break;case R.id.onebut:s1+=num_onebut.getText().toString().trim();edittext.setText(s1);break;case R.id.twobut:s1+=num_twobut.getText().toString().trim();edittext.setText(s1);break;case R.id.threebut:s1+=num_threebut.getText().toString().trim();edittext.setText(s1);break;case R.id.fourbut:s1+=num_fourbut.getText().toString().trim();edittext.setText(s1);break;case R.id.fivebut:s1+=num_fivebut.getText().toString().trim();edittext.setText(s1);break;case R.id.sixbut:s1+=num_sixbut.getText().toString().trim();edittext.setText(s1);break;case R.id.sevenbut:s1+=num_sevenbut.getText().toString().trim();edittext.setText(s1);break;case R.id.eightbut:s1+=num_eightbut.getText().toString().trim();edittext.setText(s1);break;case R.id.ninebut:s1+=num_ninebut.getText().toString().trim();edittext.setText(s1);break;case R.id.dotbut:if(s1.indexOf('.')>=0){Toast.makeText(Calculator.this, "已经出现了点", 200);}else{s1+=dotbut.getText().toString().trim();}break;case R.id.addbut:s3=addbut.getText().toString();if(flag==0){edittext.setText("");s2=s1;s1="";flag=1;}else if(flag==1){result(s3);}break;case R.id.subbut:s3=subbut.getText().toString();edittext.setText("");s2=s1;s1="";break;case R.id.multbut:s3=multbut.getText().toString();edittext.setText("");s2=s1;s1="";break;case R.id.dividebut:s3=dividebut.getText().toString();edittext.setText("");s2=s1;s1="";break;case R.id.equalbut:result(s3);flag=0;break;case R.id.clearbut:s1="";s2="";edittext.setText("");}}}private void result(String s3) {// TODO Auto-generated method stubdouble d1=Double.parseDouble(s2); //d1约等于112.0double d2=Double.parseDouble(s1);if(s3.equals("+")){result=d1+d2;s1="";s2="";edittext.setText(result+"");}else if(s3.equals("-")){result=d1-d2;s1="";s2="";edittext.setText(result+"");}else if(s3.equals("*")){result=d1*d2;s1="";s2="";edittext.setText(result+"");}else if(s3.equals("/")){if(d1==0){Toast.makeText(Calculator.this, "除数不能为零", 200).show();edittext.setText("");s1="";s2="";}else{result=d1/d2;s1="";s2="";edittext.setText(result+"");}}}}11。

安卓仿苹果计算器(内附完整源码)

安卓仿苹果计算器(内附完整源码)

//效果图:package com.jc.cal;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 MainActivity extends Activity { // 定义九个数字private Button one;private Button two;private Button three;private Button four;private Button five;private Button six;private Button seven;private Button eight;private Button nine;private Button zero;private Button dot;private Button add;private Button sub;private Button mul;private Button div;private Button clear;private Button equal;private EditText led;String num1 = "";String num2 = "";double num3 = 0;String result = "";String sign = "+";int mark = 0;boolean flag = true;boolean dotmark = true;@Overrideprotected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);setContentView(yout.activity_main);zero = (Button) findViewById(R.id.zero);one = (Button) findViewById(R.id.one);two = (Button) findViewById(R.id.two);three = (Button) findViewById(R.id.three);four = (Button) findViewById(R.id.four);five = (Button) findViewById(R.id.five);six = (Button) findViewById(R.id.six);seven = (Button) findViewById(R.id.seven);eight = (Button) findViewById(R.id.eight);nine = (Button) findViewById(R.id.nine);add = (Button) findViewById(R.id.add);sub = (Button) findViewById(R.id.sub);mul = (Button) findViewById(R.id.mul);div = (Button) findViewById(R.id.div);clear = (Button) findViewById(R.id.clear);led = (EditText) findViewById(R.id.led);equal = (Button) findViewById(R.id.equal);dot = (Button) findViewById(R.id.dot);zero.setOnClickListener(new OnClickListener() { public void onClick(View v) {if (mark == 0) {num1 = num1 + "0";led.setText(num1);} else if (mark == 1) {num2 = num2 + "0";led.setText(num1 + sign + num2);} else {num1 = String.valueOf(num3);num2 = num2 + "0";led.setText(num1 + sign + num2);}}});one.setOnClickListener(new OnClickListener() { public void onClick(View v) {if (mark == 0) {num1 = num1 + "1";led.setText(num1);} else if (mark == 1) {num2 = num2 + "1";led.setText(num1 + sign + num2);} else {num1 = String.valueOf(num3);num2 = num2 + "1";led.setText(num1 + sign + num2);}}});two.setOnClickListener(new OnClickListener() { public void onClick(View v) {if (mark == 0) {num1 = num1 + "2";led.setText(num1);} else if (mark == 1) {num2 = num2 + "2";led.setText(num1 + sign + num2);} else {num1 = String.valueOf(num3);num2 = num2 + "2";led.setText(num1 + sign + num2);}}});three.setOnClickListener(new OnClickListener() { public void onClick(View v) {if (mark == 0) {num1 = num1 + "3";led.setText(num1);} else if (mark == 1) {num2 = num2 + "3";led.setText(num1 + sign + num2);} else {num1 = String.valueOf(num3);num2 = num2 + "3";led.setText(num1 + sign + num2);}}});four.setOnClickListener(new OnClickListener() { public void onClick(View v) {if (mark == 0) {num1 = num1 + "4";led.setText(num1);} else if (mark == 1) {num2 = num2 + "4";led.setText(num1 + sign + num2);} else {num1 = String.valueOf(num3);num2 = num2 + "4";led.setText(num1 + sign + num2);}}});five.setOnClickListener(new OnClickListener() { public void onClick(View v) {if (mark == 0) {num1 = num1 + "5";led.setText(num1);} else if (mark == 1) {num2 = num2 + "5";led.setText(num1 + sign + num2);} else {num1 = String.valueOf(num3);num2 = num2 + "5";led.setText(num1 + sign + num2);}}});six.setOnClickListener(new OnClickListener() { public void onClick(View v) {if (mark == 0) {num1 = num1 + "6";led.setText(num1);} else if (mark == 1) {num2 = num2 + "6";led.setText(num1 + sign + num2);} else {num1 = String.valueOf(num3);num2 = num2 + "6";led.setText(num1 + sign + num2);}}});seven.setOnClickListener(new OnClickListener() { public void onClick(View v) {if (mark == 0) {num1 = num1 + "7";led.setText(num1);} else if (mark == 1) {num2 = num2 + "7";led.setText(num1 + sign + num2);} else {num1 = String.valueOf(num3);num2 = num2 + "7";led.setText(num1 + sign + num2);}}});eight.setOnClickListener(new OnClickListener() { public void onClick(View v) {if (mark == 0) {num1 = num1 + "8";led.setText(num1);} else if (mark == 1) {num2 = num2 + "8";led.setText(num1 + sign + num2);} else {num1 = String.valueOf(num3);num2 = num2 + "8";led.setText(num1 + sign + num2);}}});nine.setOnClickListener(new OnClickListener() { public void onClick(View v) {if (mark == 0) {num1 = num1 + "9";led.setText(num1);} else if (mark == 1) {num2 = num2 + "9";led.setText(num1 + sign + num2);} else {num1 = String.valueOf(num3);num2 = num2 + "9";led.setText(num1 + sign + num2);}}});add.setOnClickListener(new OnClickListener() { public void onClick(View v) {if (flag) {sign = "+";mark++;flag = false;dotmark = true;}}});sub.setOnClickListener(new OnClickListener() { public void onClick(View v) {if (flag) {sign = "-";mark++;flag = false;dotmark = true;}}});mul.setOnClickListener(new OnClickListener() { public void onClick(View v) {if (flag) {sign = "*";mark++;flag = false;dotmark = true;}}});div.setOnClickListener(new OnClickListener() {public void onClick(View v) {if (flag) {sign = "÷";mark++;flag = false;dotmark = true;}}});dot.setOnClickListener(new OnClickListener() {public void onClick(View v) {if (dotmark) {if (mark == 0) {num1 = num1 + ".";led.setText(num1);} else if (mark == 1) {num2 = num2 + ".";led.setText(num1 + sign + num2);} else {num1 = String.valueOf(num3);num2 = num2 + ".";led.setText(num1 + sign + num2);}dotmark = false;}}});equal.setOnClickListener(new OnClickListener() { // 等于时发生的运算public void onClick(View v) {flag = true;dotmark = true;if (sign.equals("+")) {double x = Double.parseDouble(num1);double y = Double.parseDouble(num2);num3 = x + y;result = String.valueOf(num3);led.setText(num1+ sign + num2 + "=" + result);num2 = "";} else if (sign.equals("-")) {double x = Double.parseDouble(num1);double y = Double.parseDouble(num2);num3 = x - y;result = String.valueOf(num3);led.setText(num1+ sign + num2 + "=" + result);num2 = "";} else if (sign.equals("*")) {double x = Double.parseDouble(num1);double y = Double.parseDouble(num2);num3 = x * y;result = String.valueOf(num3);led.setText(num1+ sign + num2 + "=" + result);num2 = "";} else if (sign.equals("÷")) {double x = Double.parseDouble(num1);double y = Double.parseDouble(num2);num3 = x / y;result = String.valueOf(num3);led.setText(num1+ sign + num2 + "=" + result);num2 = "";} else if (sign.equals("^")) {double x = Double.parseDouble(num1);double y = Double.parseDouble(num2);num3 = Math.pow(x, y);result = String.valueOf(num3);led.setText(num1+ sign + num2 + "=" + result);num2 = "";}}});clear.setOnClickListener(new OnClickListener() { public void onClick(View v) {num1 = "";num2 = "";num3 = 0;mark = 0;sign = "";led.setText("0");flag = true;dotmark = true;}});}}<LinearLayoutxmlns:android="/apk/res/android"xmlns:tools="/tools"android:layout_width="match_parent"android:layout_height="match_parent"android:background="#000"android:orientation="vertical"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=".MainActivity"><EditTextandroid:id="@+id/led"android:layout_width="288dp"android:layout_height="79dp"android:background="#000"android:gravity="top|right"android:text="0"android:textColor="#FFF"android:textSize="20pt"android:textStyle="bold"/><LinearLayoutandroid:layout_width="288dp"android:layout_height="70dp"android:orientation="horizontal"><Buttonandroid:id="@+id/clear"android:layout_width="70dp"android:layout_height="70dp"android:layout_margin="0.5dp"android:layout_weight="1"android:background="#C3C4C5"android:text="AC"/><Buttonandroid:layout_width="70dp"android:layout_height="70dp"android:layout_margin="0.5dp"android:layout_weight="1"android:background="#C3C4C5"android:text="+/-"/><Buttonandroid:layout_width="70dp"android:layout_height="70dp"android:layout_margin="0.5dp"android:layout_weight="1"android:background="#C3C4C5"android:text="%"/><Buttonandroid:id="@+id/div"android:layout_width="70dp"android:layout_height="70dp"android:layout_margin="0.5dp"android:layout_weight="1"android:background="#f99011"android:text="÷"/></LinearLayout><LinearLayoutandroid:layout_width="288dp"android:layout_height="70dp"android:layout_marginTop="0.5dp"android:orientation="horizontal"> <Buttonandroid:id="@+id/seven"android:layout_width="70dp"android:layout_height="70dp"android:layout_margin="0.5dp"android:layout_weight="1"android:background="#D1D2D5"android:text="7"/><Buttonandroid:id="@+id/eight"android:layout_width="70dp"android:layout_height="70dp"android:layout_margin="0.5dp"android:layout_weight="1"android:background="#D1D2D5"android:text="8"/><Buttonandroid:id="@+id/nine"android:layout_width="70dp"android:layout_height="70dp"android:layout_margin="0.5dp"android:layout_weight="1"android:background="#D1D2D5"android:text="9"/><Buttonandroid:id="@+id/mul"android:layout_width="70dp"android:layout_height="70dp"android:layout_margin="0.5dp"android:layout_weight="1"android:background="#f99011"android:text="×"/></LinearLayout><LinearLayoutandroid:layout_width="288dp"android:layout_height="70dp"android:layout_marginTop="0.5dp"android:orientation="horizontal"> <Buttonandroid:id="@+id/four"android:layout_width="70dp"android:layout_height="70dp"android:layout_margin="0.5dp"android:layout_weight="1"android:background="#D1D2D5"android:text="4"/><Buttonandroid:id="@+id/five"android:layout_width="70dp"android:layout_height="70dp"android:layout_margin="0.5dp"android:layout_weight="1"android:background="#D1D2D5"android:text="5"/><Buttonandroid:id="@+id/six"android:layout_width="70dp"android:layout_height="70dp"android:layout_margin="0.5dp"android:layout_weight="1"android:background="#D1D2D5"android:text="6"/><Buttonandroid:id="@+id/sub"android:layout_width="70dp"android:layout_height="70dp"android:layout_margin="0.5dp"android:layout_weight="1"android:background="#f99011"android:text="-"/></LinearLayout><LinearLayoutandroid:layout_width="288dp"android:layout_height="70dp"android:layout_marginTop="0.5dp"android:orientation="horizontal"> <Buttonandroid:id="@+id/one"android:layout_width="70dp"android:layout_height="70dp"android:layout_margin="0.5dp"android:layout_weight="1"android:background="#D1D2D5"android:text="1"/><Buttonandroid:id="@+id/two"android:layout_width="70dp"android:layout_height="70dp"android:layout_margin="0.5dp"android:layout_weight="1"android:background="#D1D2D5"android:text="2"/><Buttonandroid:id="@+id/three"android:layout_width="70dp"android:layout_height="70dp"android:layout_margin="0.5dp"android:layout_weight="1"android:background="#D1D2D5"android:text="3"/><Buttonandroid:id="@+id/add"android:layout_width="70dp"android:layout_height="70dp"android:layout_margin="0.5dp"android:layout_weight="1"android:background="#f99011"android:text="+"/></LinearLayout><LinearLayoutandroid:layout_width="288dp"android:layout_height="70dp"android:layout_marginTop="0.5dp"android:orientation="horizontal"><Buttonandroid:id="@+id/zero"android:layout_width="141.5dp"android:layout_height="70dp"android:layout_margin="0.5dp"android:layout_weight="1"android:background="#D1D2D5"android:text="0"/><Buttonandroid:id="@+id/dot"android:layout_width="69.5dp"android:layout_height="70dp"android:layout_margin="0.5dp"android:layout_weight="1"android:background="#D1D2D5"android:text="."/><Buttonandroid:id="@+id/equal"android:layout_width="68.5dp"android:layout_height="70dp"android:layout_margin="0.5dp"android:layout_weight="1"android:background="#f99011"android:onClick="enterInfo"android:text="="/></LinearLayout></LinearLayout>。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

//效果图:package com.jc.cal;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 MainActivity extends Activity { // 定义九个数字private Button one;private Button two;private Button three;private Button four;private Button five;private Button six;private Button seven;private Button eight;private Button nine;private Button zero;private Button dot;private Button add;private Button sub;private Button mul;private Button div;private Button clear;private Button equal;private EditText led;String num1 = "";String num2 = "";double num3 = 0;String result = "";String sign = "+";int mark = 0;boolean flag = true;boolean dotmark = true;@Overrideprotected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);setContentView(yout.activity_main);zero = (Button) findViewById(R.id.zero);one = (Button) findViewById(R.id.one);two = (Button) findViewById(R.id.two);three = (Button) findViewById(R.id.three);four = (Button) findViewById(R.id.four);five = (Button) findViewById(R.id.five);six = (Button) findViewById(R.id.six);seven = (Button) findViewById(R.id.seven);eight = (Button) findViewById(R.id.eight);nine = (Button) findViewById(R.id.nine);add = (Button) findViewById(R.id.add);sub = (Button) findViewById(R.id.sub);mul = (Button) findViewById(R.id.mul);div = (Button) findViewById(R.id.div);clear = (Button) findViewById(R.id.clear);led = (EditText) findViewById(R.id.led);equal = (Button) findViewById(R.id.equal);dot = (Button) findViewById(R.id.dot);zero.setOnClickListener(new OnClickListener() { public void onClick(View v) {if (mark == 0) {num1 = num1 + "0";led.setText(num1);} else if (mark == 1) {num2 = num2 + "0";led.setText(num1 + sign + num2);} else {num1 = String.valueOf(num3);num2 = num2 + "0";led.setText(num1 + sign + num2);}}});one.setOnClickListener(new OnClickListener() { public void onClick(View v) {if (mark == 0) {num1 = num1 + "1";led.setText(num1);} else if (mark == 1) {num2 = num2 + "1";led.setText(num1 + sign + num2);} else {num1 = String.valueOf(num3);num2 = num2 + "1";led.setText(num1 + sign + num2);}}});two.setOnClickListener(new OnClickListener() { public void onClick(View v) {if (mark == 0) {num1 = num1 + "2";led.setText(num1);} else if (mark == 1) {num2 = num2 + "2";led.setText(num1 + sign + num2);} else {num1 = String.valueOf(num3);num2 = num2 + "2";led.setText(num1 + sign + num2);}}});three.setOnClickListener(new OnClickListener() { public void onClick(View v) {if (mark == 0) {num1 = num1 + "3";led.setText(num1);} else if (mark == 1) {num2 = num2 + "3";led.setText(num1 + sign + num2);} else {num1 = String.valueOf(num3);num2 = num2 + "3";led.setText(num1 + sign + num2);}}});four.setOnClickListener(new OnClickListener() { public void onClick(View v) {if (mark == 0) {num1 = num1 + "4";led.setText(num1);} else if (mark == 1) {num2 = num2 + "4";led.setText(num1 + sign + num2);} else {num1 = String.valueOf(num3);num2 = num2 + "4";led.setText(num1 + sign + num2);}}});five.setOnClickListener(new OnClickListener() { public void onClick(View v) {if (mark == 0) {num1 = num1 + "5";led.setText(num1);} else if (mark == 1) {num2 = num2 + "5";led.setText(num1 + sign + num2);} else {num1 = String.valueOf(num3);num2 = num2 + "5";led.setText(num1 + sign + num2);}}});six.setOnClickListener(new OnClickListener() { public void onClick(View v) {if (mark == 0) {num1 = num1 + "6";led.setText(num1);} else if (mark == 1) {num2 = num2 + "6";led.setText(num1 + sign + num2);} else {num1 = String.valueOf(num3);num2 = num2 + "6";led.setText(num1 + sign + num2);}}});seven.setOnClickListener(new OnClickListener() { public void onClick(View v) {if (mark == 0) {num1 = num1 + "7";led.setText(num1);} else if (mark == 1) {num2 = num2 + "7";led.setText(num1 + sign + num2);} else {num1 = String.valueOf(num3);num2 = num2 + "7";led.setText(num1 + sign + num2);}}});eight.setOnClickListener(new OnClickListener() { public void onClick(View v) {if (mark == 0) {num1 = num1 + "8";led.setText(num1);} else if (mark == 1) {num2 = num2 + "8";led.setText(num1 + sign + num2);} else {num1 = String.valueOf(num3);num2 = num2 + "8";led.setText(num1 + sign + num2);}}});nine.setOnClickListener(new OnClickListener() { public void onClick(View v) {if (mark == 0) {num1 = num1 + "9";led.setText(num1);} else if (mark == 1) {num2 = num2 + "9";led.setText(num1 + sign + num2);} else {num1 = String.valueOf(num3);num2 = num2 + "9";led.setText(num1 + sign + num2);}}});add.setOnClickListener(new OnClickListener() { public void onClick(View v) {if (flag) {sign = "+";mark++;flag = false;dotmark = true;}}});sub.setOnClickListener(new OnClickListener() { public void onClick(View v) {if (flag) {sign = "-";mark++;flag = false;dotmark = true;}}});mul.setOnClickListener(new OnClickListener() { public void onClick(View v) {if (flag) {sign = "*";mark++;flag = false;dotmark = true;}}});div.setOnClickListener(new OnClickListener() {public void onClick(View v) {if (flag) {sign = "÷";mark++;flag = false;dotmark = true;}}});dot.setOnClickListener(new OnClickListener() {public void onClick(View v) {if (dotmark) {if (mark == 0) {num1 = num1 + ".";led.setText(num1);} else if (mark == 1) {num2 = num2 + ".";led.setText(num1 + sign + num2);} else {num1 = String.valueOf(num3);num2 = num2 + ".";led.setText(num1 + sign + num2);}dotmark = false;}}});equal.setOnClickListener(new OnClickListener() { // 等于时发生的运算public void onClick(View v) {flag = true;dotmark = true;if (sign.equals("+")) {double x = Double.parseDouble(num1);double y = Double.parseDouble(num2);num3 = x + y;result = String.valueOf(num3);led.setText(num1+ sign + num2 + "=" + result);num2 = "";} else if (sign.equals("-")) {double x = Double.parseDouble(num1);double y = Double.parseDouble(num2);num3 = x - y;result = String.valueOf(num3);led.setText(num1+ sign + num2 + "=" + result);num2 = "";} else if (sign.equals("*")) {double x = Double.parseDouble(num1);double y = Double.parseDouble(num2);num3 = x * y;result = String.valueOf(num3);led.setText(num1+ sign + num2 + "=" + result);num2 = "";} else if (sign.equals("÷")) {double x = Double.parseDouble(num1);double y = Double.parseDouble(num2);num3 = x / y;result = String.valueOf(num3);led.setText(num1+ sign + num2 + "=" + result);num2 = "";} else if (sign.equals("^")) {double x = Double.parseDouble(num1);double y = Double.parseDouble(num2);num3 = Math.pow(x, y);result = String.valueOf(num3);led.setText(num1+ sign + num2 + "=" + result);num2 = "";}}});clear.setOnClickListener(new OnClickListener() { public void onClick(View v) {num1 = "";num2 = "";num3 = 0;mark = 0;sign = "";led.setText("0");flag = true;dotmark = true;}});}}<LinearLayoutxmlns:android="/apk/res/android"xmlns:tools="/tools"android:layout_width="match_parent"android:layout_height="match_parent"android:background="#000"android:orientation="vertical"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=".MainActivity"><EditTextandroid:id="@+id/led"android:layout_width="288dp"android:layout_height="79dp"android:background="#000"android:gravity="top|right"android:text="0"android:textColor="#FFF"android:textSize="20pt"android:textStyle="bold"/><LinearLayoutandroid:layout_width="288dp"android:layout_height="70dp"android:orientation="horizontal"><Buttonandroid:id="@+id/clear"android:layout_width="70dp"android:layout_height="70dp"android:layout_margin="0.5dp"android:layout_weight="1"android:background="#C3C4C5"android:text="AC"/><Buttonandroid:layout_width="70dp"android:layout_height="70dp"android:layout_margin="0.5dp"android:layout_weight="1"android:background="#C3C4C5"android:text="+/-"/><Buttonandroid:layout_width="70dp"android:layout_height="70dp"android:layout_margin="0.5dp"android:layout_weight="1"android:background="#C3C4C5"android:text="%"/><Buttonandroid:id="@+id/div"android:layout_width="70dp"android:layout_height="70dp"android:layout_margin="0.5dp"android:layout_weight="1"android:background="#f99011"android:text="÷"/></LinearLayout><LinearLayoutandroid:layout_width="288dp"android:layout_height="70dp"android:layout_marginTop="0.5dp"android:orientation="horizontal"> <Buttonandroid:id="@+id/seven"android:layout_width="70dp"android:layout_height="70dp"android:layout_margin="0.5dp"android:layout_weight="1"android:background="#D1D2D5"android:text="7"/><Buttonandroid:id="@+id/eight"android:layout_width="70dp"android:layout_height="70dp"android:layout_margin="0.5dp"android:layout_weight="1"android:background="#D1D2D5"android:text="8"/><Buttonandroid:id="@+id/nine"android:layout_width="70dp"android:layout_height="70dp"android:layout_margin="0.5dp"android:layout_weight="1"android:background="#D1D2D5"android:text="9"/><Buttonandroid:id="@+id/mul"android:layout_width="70dp"android:layout_height="70dp"android:layout_margin="0.5dp"android:layout_weight="1"android:background="#f99011"android:text="×"/></LinearLayout><LinearLayoutandroid:layout_width="288dp"android:layout_height="70dp"android:layout_marginTop="0.5dp"android:orientation="horizontal"> <Buttonandroid:id="@+id/four"android:layout_width="70dp"android:layout_height="70dp"android:layout_margin="0.5dp"android:layout_weight="1"android:background="#D1D2D5"android:text="4"/><Buttonandroid:id="@+id/five"android:layout_width="70dp"android:layout_height="70dp"android:layout_margin="0.5dp"android:layout_weight="1"android:background="#D1D2D5"android:text="5"/><Buttonandroid:id="@+id/six"android:layout_width="70dp"android:layout_height="70dp"android:layout_margin="0.5dp"android:layout_weight="1"android:background="#D1D2D5"android:text="6"/><Buttonandroid:id="@+id/sub"android:layout_width="70dp"android:layout_height="70dp"android:layout_margin="0.5dp"android:layout_weight="1"android:background="#f99011"android:text="-"/></LinearLayout><LinearLayoutandroid:layout_width="288dp"android:layout_height="70dp"android:layout_marginTop="0.5dp"android:orientation="horizontal"> <Buttonandroid:id="@+id/one"android:layout_width="70dp"android:layout_height="70dp"android:layout_margin="0.5dp"android:layout_weight="1"android:background="#D1D2D5"android:text="1"/><Buttonandroid:id="@+id/two"android:layout_width="70dp"android:layout_height="70dp"android:layout_margin="0.5dp"android:layout_weight="1"android:background="#D1D2D5"android:text="2"/><Buttonandroid:id="@+id/three"android:layout_width="70dp"android:layout_height="70dp"android:layout_margin="0.5dp"android:layout_weight="1"android:background="#D1D2D5"android:text="3"/><Buttonandroid:id="@+id/add"android:layout_width="70dp"android:layout_height="70dp"android:layout_margin="0.5dp"android:layout_weight="1"android:background="#f99011"android:text="+"/></LinearLayout><LinearLayoutandroid:layout_width="288dp"android:layout_height="70dp"android:layout_marginTop="0.5dp"android:orientation="horizontal"><Buttonandroid:id="@+id/zero"android:layout_width="141.5dp"android:layout_height="70dp"android:layout_margin="0.5dp"android:layout_weight="1"android:background="#D1D2D5"android:text="0"/><Buttonandroid:id="@+id/dot"android:layout_width="69.5dp"android:layout_height="70dp"android:layout_margin="0.5dp"android:layout_weight="1"android:background="#D1D2D5"android:text="."/><Buttonandroid:id="@+id/equal"android:layout_width="68.5dp"android:layout_height="70dp"android:layout_margin="0.5dp"android:layout_weight="1"android:background="#f99011"android:onClick="enterInfo"android:text="="/></LinearLayout></LinearLayout>。

相关文档
最新文档