parent
6059a8fdbf
commit
605fe6755f
@ -0,0 +1,30 @@
|
||||
package calculator;
|
||||
|
||||
import javafx.application.Application;
|
||||
import javafx.fxml.FXMLLoader;
|
||||
import javafx.scene.Scene;
|
||||
import javafx.scene.layout.GridPane;
|
||||
import javafx.stage.Stage;
|
||||
|
||||
public class Calculator extends Application {
|
||||
|
||||
public static void main(String[] args) {
|
||||
launch(args);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void start(Stage primaryStage) {
|
||||
primaryStage.setTitle("简单计算器");
|
||||
|
||||
try {
|
||||
FXMLLoader loader = new FXMLLoader(getClass().getResource("CalculatorView.fxml"));
|
||||
GridPane gridPane = loader.load();
|
||||
|
||||
Scene scene = new Scene(gridPane, 250, 250);
|
||||
primaryStage.setScene(scene);
|
||||
primaryStage.show();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,70 @@
|
||||
package calculator;
|
||||
|
||||
import javafx.fxml.FXML;
|
||||
import javafx.scene.control.Button;
|
||||
import javafx.scene.control.TextField;
|
||||
|
||||
public class CalculatorController {
|
||||
@FXML
|
||||
private TextField textField;
|
||||
|
||||
@FXML
|
||||
public void handleButtonAction(javafx.event.ActionEvent event) {
|
||||
Button button = (Button) event.getSource();
|
||||
String buttonText = button.getText();
|
||||
|
||||
switch (buttonText) {
|
||||
case "=":
|
||||
calculateResult();
|
||||
break;
|
||||
case "C":
|
||||
textField.clear();
|
||||
break;
|
||||
default:
|
||||
appendToTextField(buttonText);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private void appendToTextField(String value) {
|
||||
textField.appendText(value);
|
||||
}
|
||||
|
||||
private void calculateResult() {
|
||||
String expression = textField.getText();
|
||||
try {
|
||||
double result = evaluate(expression);
|
||||
textField.setText(String.valueOf(result));
|
||||
} catch (Exception e) {
|
||||
textField.setText("错误");
|
||||
}
|
||||
}
|
||||
|
||||
private double evaluate(String expression) {
|
||||
String[] tokens = expression.split(" ");
|
||||
double result = Double.parseDouble(tokens[0]);
|
||||
for (int i = 1; i < tokens.length; i += 2) {
|
||||
String operator = tokens[i];
|
||||
double nextNumber = Double.parseDouble(tokens[i + 1]);
|
||||
switch (operator) {
|
||||
case "+":
|
||||
result += nextNumber;
|
||||
break;
|
||||
case "-":
|
||||
result -= nextNumber;
|
||||
break;
|
||||
case "*":
|
||||
result *= nextNumber;
|
||||
break;
|
||||
case "/":
|
||||
if (nextNumber != 0) {
|
||||
result /= nextNumber;
|
||||
} else {
|
||||
throw new ArithmeticException("除数不能为零");
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
Loading…
Reference in new issue