When illegal input is not considered:
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 (The new Scene (root, N.)); Stage.show (); } public boolean check (int num) { Boolean re = false; if (num% 4) = = 0) re = true; if (num%) = = 0) re = false; if (num%) = = 0) re = true; return re; }}
Normal input:
Illegal input:
Cause Analysis:
The use of the Integer.parseint (Tf.gettext ()) function does not take into account the case of illegal input.
Improved:
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!");}} );
Effect:
Leap Year test program