综合实战:简单计算器的参考设计方法(1)

1.实验内容简介

综合使用文本框,编辑框,下拉框和按钮,设计一款简单的四则计算器,即可以实现加减乘除四则运算。

附加功能:

保存最后一次运算的结果。

参考之前做过的练习,灵活运用所学的知识。提示:

(1)int整数类型无法满足乘法和除法的运算,要用浮点类型float。

(2)Float类型与字符串类型转换用Float.parseFloat();

(3)字符串类型与Float类型转换用String.valueOf();

(4)Spinner下拉框不熟悉的,也可以考虑用RadioGroup和RadioButton实现四则运算的选择。

(5)参考lingsizhiyuan公众号上面做过的例子。

2. UI界面布局

对应的大纲:

3.代码编写和调试

publicclass MainActivity extends Activity {

private EditText editTextNum1, editTextNum2;

private TextView textViewJieguo;

private Spinner spinner1;

private Button buttonJisuan;

private int calPositon;

private static final String[] mCal = {"+", "-", "*", "/" };

private ArrayList mCalList;

private ArrayAdapteradapterCal;

private float num1, num2, jieguo;

@Override

protected void onCreate(BundlesavedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

editTextNum1 = (EditText)this.findViewById(R.id.editTextNum1);

editTextNum2 = (EditText)this.findViewById(R.id.editTextNum2);

textViewJieguo = (TextView)this.findViewById(R.id.textViewJieguo);

buttonJisuan = (Button)this.findViewById(R.id.buttonJisuan);

spinner1 = (Spinner)this.findViewById(R.id.spinner1);

mCalList = new ArrayList();

for (int i = 0; i

mCalList.add(mCal[i]);

}

adapterCal = new ArrayAdapter(this,

android.R.layout.simple_spinner_item,mCalList);

adapterCal

.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

spinner1.setAdapter(adapterCal);

spinner1.setOnItemSelectedListener(newOnItemSelectedListener() {

@Override

public void onItemSelected(AdapterView parent, View view,

int position, long id) {

calPositon = position;

Toast.makeText(getApplicationContext(),

parent.getItemAtPosition(position).toString(),

Toast.LENGTH_LONG).show();

}

@Override

public void onNothingSelected(AdapterView parent) {

}

});

buttonJisuan.setOnClickListener(newOnClickListener() {

@Override

public void onClick(View v) {

if(editTextNum1.getText().toString().isEmpty()

||editTextNum2.getText().toString().isEmpty()) {

Toast.makeText(MainActivity.this,"请输入", Toast.LENGTH_SHORT)

.show();

return;

}

num1 =Float.parseFloat(editTextNum1.getText().toString());

num2 =Float.parseFloat(editTextNum2.getText().toString());

switch (calPositon) {

case 0:

jieguo = num1 + num2;

break;

case 1:

jieguo = num1 - num2;

break;

case 2:

jieguo = num1 * num2;

break;

case 3:

jieguo = num1 / num2;

break;

}

textViewJieguo.setText(String.valueOf(jieguo));

}

});

}

}

  • 发表于:
  • 原文链接https://kuaibao.qq.com/s/20180519G008Y900?refer=cp_1026
  • 腾讯「云+社区」是腾讯内容开放平台帐号(企鹅号)传播渠道之一,根据《腾讯内容开放平台服务协议》转载发布内容。
  • 如有侵权,请联系 yunjia_community@tencent.com 删除。

同媒体快讯

扫码关注云+社区

领取腾讯云代金券