我需要使用异常处理来在添加数字时捕获不正确的数值。我有我创建的代码,但我不知道该怎么做。有人可以告诉我它是如何正确完成的,所以我知道未来。
import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.event.*;
import javafx.stage.Stage;
public class test33 extends Application {
private double num1 = 0, num2 = 0, result = 0;
@Override
// Override the start method in the Application class
public void start(Stage primaryStage) {
FlowPane pane = new FlowPane();
pane.setHgap(2);
TextField tfNumber1 = new TextField();
TextField tfNumber2 = new TextField();
TextField tfResult = new TextField();
tfNumber1.setPrefColumnCount(3);
tfNumber2.setPrefColumnCount(3);
tfResult.setPrefColumnCount(3);
pane.getChildren().addAll(new Label("Number 1: "), tfNumber1,
new Label("Number 2: "), tfNumber2, new Label("Result: "), tfResult);
// Create four buttons
HBox hBox = new HBox(5);
Button btAdd = new Button("Add");
hBox.setAlignment(Pos.CENTER);
hBox.getChildren().addAll(btAdd);
BorderPane borderPane = new BorderPane();
borderPane.setCenter(pane);
borderPane.setBottom(hBox);
BorderPane.setAlignment(hBox, Pos.TOP_CENTER);
// Create a scene and place it in the stage
Scene scene = new Scene(borderPane, 375, 150);
primaryStage.setTitle("Test33"); // Set the stage title
primaryStage.setScene(scene); // Place the scene in the stage
primaryStage.show(); // Display the stage
btAdd.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent e) {
num1 = Double.parseDouble(tfNumber1.getText());
num2 = Double.parseDouble(tfNumber2.getText());
result = num1 + num2;
tfResult.setText(String.format("%.1f", result));
}
});
}
/**
* The main method is only needed for the IDE with limited
* JavaFX support. Not needed for running from the command line.
*/
public static void main(String[] args) {
launch(args);
}
}
答案 0 :(得分:1)
应该存在的异常处理的一个方面是.parseDouble()
。我建议至少添加NumberFormatException处理
public void handle(ActionEvent e) {
try {
num1 = Double.parseDouble(tfNumber1.getText());
num2 = Double.parseDouble(tfNumber2.getText());
result = num1 + num2;
tfResult.setText(String.format("%.1f", result));
}
catch (NumberFormatException nfe) {
tfResult.setText("Invalid input!");
}
}
通过捕获导致错误的特定输入等,可以获得更细粒度。但是,从捕获错误数字的演示角度来看,此代码是说明性的。