if (button.equals("C")) { // clear txtResult.setText(""); num1 = 0; num2 = 0; op = ""; } else if (button.equals("+")) { // addition num1 = Double.parseDouble(txtResult.getText()); op = "+"; txtResult.setText(""); } else if (button.equals("-")) { // subtraction num1 = Double.parseDouble(txtResult.getText()); op = "-"; txtResult.setText(""); } else if (button.equals("*")) { // multiplication num1 = Double.parseDouble(txtResult.getText()); op = "*"; txtResult.setText(""); } else if (button.equals("/")) { // division num1 = Double.parseDouble(txtResult.getText()); op = "/"; txtResult.setText(""); } else if (button.equals("=")) { // equals num2 = Double.parseDouble(txtResult.getText()); if (op.equals("+")) { txtResult.setText(Double.toString(num1 + num2)); } else if (op.equals("-")) { txtResult.setText(Double.toString(num1 - num2)); } else if (op.equals("*")) { txtResult.setText(Double.toString(num1 * num2)); } else if (op.equals("/")) { txtResult.setText(Double.toString(num1 / num2)); } } else { // digit txtResult.setText(txtResult.getText() + button); }改用switch语句
时间: 2023-06-20 16:09:45 浏览: 94
可以将上述代码改写为使用 switch 语句的形式,代码如下所示:
```
switch (button) {
case "C":
txtResult.setText("");
num1 = 0;
num2 = 0;
op = "";
break;
case "+":
num1 = Double.parseDouble(txtResult.getText());
op = "+";
txtResult.setText("");
break;
case "-":
num1 = Double.parseDouble(txtResult.getText());
op = "-";
txtResult.setText("");
break;
case "*":
num1 = Double.parseDouble(txtResult.getText());
op = "*";
txtResult.setText("");
break;
case "/":
num1 = Double.parseDouble(txtResult.getText());
op = "/";
txtResult.setText("");
break;
case "=":
num2 = Double.parseDouble(txtResult.getText());
switch (op) {
case "+":
txtResult.setText(Double.toString(num1 + num2));
break;
case "-":
txtResult.setText(Double.toString(num1 - num2));
break;
case "*":
txtResult.setText(Double.toString(num1 * num2));
break;
case "/":
txtResult.setText(Double.toString(num1 / num2));
break;
}
break;
default:
txtResult.setText(txtResult.getText() + button);
break;
}
```
使用 switch 语句可以使代码更加简洁易读,并且能够避免出现多个 if 语句嵌套的情况。
阅读全文