【发布时间】:2016-04-07 22:09:40
【问题描述】:
添加数字时,我需要使用异常处理来捕获不正确的数值。我有我创建的代码,但我不知道该怎么做。有人可以告诉我它是如何正确完成的,以便我知道未来。
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);
}
}
【问题讨论】:
-
什么是“不正确的数值”?只是它不是某种数字(例如,在 tfNumber1 中输入“asdf”)?还是有其他考虑(例如,不能为负数)?
标签: java exception javafx exception-handling