写一个Android Studio 计算器代码
时间: 2023-11-02 22:01:40 浏览: 105
当然,我很乐意帮您写一个Android Studio计算器代码!以下是一个基本的示例:
```java
public class MainActivity extends AppCompatActivity {
private String currentNumber = "";
private String currentOperation = "";
private TextView resultTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
resultTextView = (TextView)findViewById(R.id.resultTextView);
resultTextView.setKeyListener(null);
}
public void onNumberButtonClick(View view) {
Button button = (Button)view;
currentNumber += button.getText().toString();
updateResult();
}
public void onOperationButtonClick(View view) {
Button button = (Button)view;
String operation = button.getText().toString().toLowerCase();
if (operation.equals("=")) {
calculate();
return;
}
if (!currentNumber.isEmpty()) {
calculate();
}
currentOperation = operation;
updateResult();
}
private void calculate() {
if (!currentOperation.isEmpty()) {
double currentValue = Double.parseDouble(currentNumber);
double resultValue = 0;
if (currentOperation.equals("+")) {
resultValue = currentValue + Double.parseDouble(resultTextView.getText().toString());
} else if (currentOperation.equals("-")) {
resultValue = Double.parseDouble(resultTextView.getText().toString()) - currentValue;
} else if (currentOperation.equals("x")) {
resultValue = currentValue * Double.parseDouble(resultTextView.getText().toString());
} else if (currentOperation.equals("/")) {
if (currentValue != 0) {
resultValue = Double.parseDouble(resultTextView.getText().toString()) / currentValue;
} else {
Toast.makeText(this, "Cannot divide by zero", Toast.LENGTH_LONG).show();
return;
}
}
resultTextView.setText(String.valueOf(resultValue));
currentNumber = "";
currentOperation = "";
}
}
public void onClearButtonClick(View view) {
currentNumber = "";
currentOperation = "";
resultTextView.setText("");
}
private void updateResult() {
resultTextView.setText(currentNumber + " " + currentOperation);
}
}
```
这段代码实现了一个简单的四则运算计算器,您可以将其复制到您的Android Studio项目中,并对其进行适当修改,以满足您的实际需求。希望对您有所帮助!
阅读全文