android studio 进行连续无优先级加减乘除的计算器代码
时间: 2023-11-02 16:06:44 浏览: 104
android studio计算器实现代码
以下是一个基本的Android Studio计算器代码,可以进行加减乘除的运算:
```java
public class MainActivity extends AppCompatActivity {
private EditText editText;
private String currentOperator = "";
private double firstNumber = 0;
private boolean operatorPressed = false;
private boolean decimalPressed = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = findViewById(R.id.editText);
editText.setKeyListener(null);
}
public void onNumberClick(View view) {
Button button = (Button) view;
String buttonText = button.getText().toString();
String currentText = editText.getText().toString();
if (currentText.equals("0")) {
editText.setText(buttonText);
} else {
editText.setText(currentText + buttonText);
}
operatorPressed = false;
}
public void onOperatorClick(View view) {
Button button = (Button) view;
String buttonText = button.getText().toString();
if (operatorPressed) {
currentOperator = buttonText;
return;
}
if (firstNumber == 0) {
firstNumber = Double.parseDouble(editText.getText().toString());
} else {
double secondNumber = Double.parseDouble(editText.getText().toString());
switch (currentOperator) {
case "+":
firstNumber += secondNumber;
break;
case "-":
firstNumber -= secondNumber;
break;
case "×":
firstNumber *= secondNumber;
break;
case "÷":
firstNumber /= secondNumber;
break;
}
}
currentOperator = buttonText;
operatorPressed = true;
decimalPressed = false;
}
public void onClearClick(View view) {
firstNumber = 0;
currentOperator = "";
operatorPressed = false;
decimalPressed = false;
editText.setText("0");
}
public void onDecimalClick(View view) {
if (decimalPressed) {
return;
}
String currentText = editText.getText().toString();
editText.setText(currentText + ".");
decimalPressed = true;
}
public void onEqualClick(View view) {
if (operatorPressed) {
return;
}
double secondNumber = Double.parseDouble(editText.getText().toString());
switch (currentOperator) {
case "+":
firstNumber += secondNumber;
break;
case "-":
firstNumber -= secondNumber;
break;
case "×":
firstNumber *= secondNumber;
break;
case "÷":
firstNumber /= secondNumber;
break;
}
editText.setText(String.valueOf(firstNumber));
operatorPressed = true;
decimalPressed = false;
}
}
```
在此代码中,我们使用了四个按钮,分别对应数字、加号、减号、乘号、除号、小数点和清除。我们在onNumberClick()函数中处理了数字按钮的点击事件,将每个数字附加到文本框中。在onOperatorClick()函数中处理运算符按钮的点击事件,根据当前选择的运算符执行相应的计算。在onClearClick()函数中处理清除按钮的点击事件,将文本框重置为0。在onDecimalClick()函数中处理小数点按钮的点击事件,我们确保只添加一个小数点。最后,在onEqualClick()函数中处理等于按钮的点击事件,完成最终的计算。
阅读全文