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));
}
});
}
}
领取专属 10元无门槛券
私享最新 技术干货