帮我写一个安卓计算器可以实现连乘连加的MainActivity代码
时间: 2023-06-15 19:05:09 浏览: 235
安卓代码实现计算器
5星 · 资源好评率100%
好的,以下是一个简单的安卓计算器实现连乘连加的 MainActivity 代码:
```java
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private EditText etResult;
private Button btnClear, btnDelete, btnDivide, btnMultiply, btnMinus, btnPlus, btnEqual;
private Button[] btnNums;
private StringBuilder sb = new StringBuilder();
private double num1 = 0, num2 = 0;
private int operator = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etResult = findViewById(R.id.et_result);
btnClear = findViewById(R.id.btn_clear);
btnDelete = findViewById(R.id.btn_delete);
btnDivide = findViewById(R.id.btn_divide);
btnMultiply = findViewById(R.id.btn_multiply);
btnMinus = findViewById(R.id.btn_minus);
btnPlus = findViewById(R.id.btn_plus);
btnEqual = findViewById(R.id.btn_equal);
btnNums = new Button[10];
for (int i = 0; i < 10; i++) {
String btnId = "btn_" + i;
int resId = getResources().getIdentifier(btnId, "id", getPackageName());
btnNums[i] = findViewById(resId);
}
btnClear.setOnClickListener(this);
btnDelete.setOnClickListener(this);
btnDivide.setOnClickListener(this);
btnMultiply.setOnClickListener(this);
btnMinus.setOnClickListener(this);
btnPlus.setOnClickListener(this);
btnEqual.setOnClickListener(this);
for (Button btnNum : btnNums) {
btnNum.setOnClickListener(this);
}
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_clear:
clear();
break;
case R.id.btn_delete:
delete();
break;
case R.id.btn_divide:
operator = 4;
num1 = Double.parseDouble(sb.toString());
sb.delete(0, sb.length());
break;
case R.id.btn_multiply:
operator = 3;
num1 = Double.parseDouble(sb.toString());
sb.delete(0, sb.length());
break;
case R.id.btn_minus:
operator = 2;
num1 = Double.parseDouble(sb.toString());
sb.delete(0, sb.length());
break;
case R.id.btn_plus:
operator = 1;
num1 = Double.parseDouble(sb.toString());
sb.delete(0, sb.length());
break;
case R.id.btn_equal:
num2 = Double.parseDouble(sb.toString());
sb.delete(0, sb.length());
double result = 0;
switch (operator) {
case 1:
result = num1 + num2;
break;
case 2:
result = num1 - num2;
break;
case 3:
result = num1 * num2;
break;
case 4:
result = num1 / num2;
break;
}
etResult.setText(String.valueOf(result));
break;
default:
sb.append(((Button) v).getText());
etResult.setText(sb.toString());
break;
}
}
private void clear() {
num1 = 0;
num2 = 0;
operator = 0;
sb.delete(0, sb.length());
etResult.setText("");
}
private void delete() {
if (sb.length() > 0) {
sb.deleteCharAt(sb.length() - 1);
etResult.setText(sb.toString());
}
}
}
```
这个计算器可以实现加、减、乘、除和连乘连加的功能。在按钮点击事件中,我们可以根据操作符进行相应的运算。当用户点击等号时,我们可以根据操作符计算出结果并显示在 EditText 中。
阅读全文