标签:
未考虑非法输入时:
import javafx.application.Application; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.TextField; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.HBox; import javafx.scene.text.Text; import javafx.stage.Stage; public class Test extends Application{ public static void main(String[] args) { Test.launch(args); } public void start(Stage stage ){ stage.setTitle("Year Testing"); AnchorPane root = new AnchorPane(); HBox hbox1 = new HBox(8); Text text = new Text("The Number of Year: "); final Text result = new Text(); final TextField tf = new TextField(); Button btn = new Button("Enter"); hbox1.getChildren().addAll(text, tf, btn); btn.setOnAction(new EventHandler<ActionEvent>(){ @Override public void handle(ActionEvent actEvt) { if(check(Integer.parseInt(tf.getText()))) result.setText(Integer.parseInt(tf.getText())+" Good"); else result.setText(Integer.parseInt(tf.getText())+" Bad"); } }); AnchorPane.setTopAnchor(hbox1, 60.0); AnchorPane.setLeftAnchor(hbox1, 30.0); root.getChildren().add(hbox1); AnchorPane.setTopAnchor(result, 90.0); AnchorPane.setLeftAnchor(result, 30.0); root.getChildren().
add(result); stage.setScene(new Scene(root, 400, 200)); stage.show(); } public boolean check(int num){ boolean re = false; if((num % 4) == 0) re = true; if((num % 100) == 0) re = false; if((num % 400) == 0) re = true; return re; } }
正常输入:
非法输入:
原因分析:
在使用Integer.parseInt(tf.getText())函数时没有考虑到非法输入的情况。
改进:
btn.setOnAction(new EventHandler<ActionEvent>(){ @Override public void handle(ActionEvent actEvt) { try{ if(check(Integer.parseInt(tf.getText()))) result.setText(Integer.parseInt(tf.getText())+" Good"); else result.setText(Integer.parseInt(tf.getText())+" Bad"); } catch(Exception e){ result.setText("Illegal Input!"); } } });
效果:
标签:
原文地址:http://www.cnblogs.com/tan1994/p/4397157.html