@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); init(); } public void init(){ input1 = (EditText)findViewById(R.id.input_1); input2 = (EditText)findViewById(R.id.input_2); jia = (Button)findViewById(R.id.jia); jian = (Button)findViewById(R.id.jian); cheng = (Button)findViewById(R.id.cheng); chu = (Button)findViewById(R.id.chu); fuhao = (TextView)findViewById(R.id.fuhao); re = (TextView)findViewById(R.id.RE); } public void jia(View view){ boolean b = getNumer(); if(b==false) return;//如果为空,则停止 fuhao.setText("+"); double a =Algorithm.jiafa(in, in2); re.setText(a+""); } public void jian(View view){ boolean b = getNumer(); if(b==false) return;//如果为空,则停止 fuhao.setText("-"); double a =Algorithm.jianfa(in, in2); re.setText(a+""); } public void cheng(View view){ boolean b = getNumer(); if(b==false) return;//如果为空,则停止 fuhao.setText("*"); double a =Algorithm.chengfa(in, in2); re.setText(a+""); } public void chu(View view){ boolean b = getNumer(); if(b==false) return; //如果为空,则停止 fuhao.setText("/"); double a =Algorithm.chufa(in, in2); re.setText(a+""); } /** * 获取文本并检查是否为空 */ public boolean getNumer(){ in = input1.getText().toString(); in2 = input2.getText().toString(); if(in.equals("")||in2.equals("")){ Toast.makeText(MainActivity.this,"请输入", Toast.LENGTH_SHORT).show(); return false; } return true; } /** * 设置菜单的点击事件 */ @Override public boolean onOptionsItemSelected(MenuItem item) {
int i = item.getItemId(); switch (i) { //点击关于,弹出对话框 case R.id.about: AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this); alertDialog.setTitle("说明") .setMessage("作者:0000"+"\n"+"版本:111.0.0.0") .setPositiveButton("确定", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int arg1) { dialog.dismiss(); } }).show();
package cn.edu.bzu.counter.algorithm; import android.content.Context; import android.widget.Toast; public class Algorithm {
public static double jiafa(String in, String in2){ double a =Double.parseDouble(in); double b = Double.parseDouble(in2); return a+b; } public static double jianfa(String in, String in2){ double a =Double.parseDouble(in); double b = Double.parseDouble(in2); return a-b; } public static double chengfa(String in, String in2){ double a =Double.parseDouble(in); double b = Double.parseDouble(in2); return a*b; } /** * 抛出异常,防止除数为0 */ public static double chufa(String in, String in2) throws ArithmeticException{ double a =Double.parseDouble(in); double b = Double.parseDouble(in2); return a/b; }