Problem implementation
The Java code that implements a leap year test is as follows:
Packageleapyear;Importjava.awt.event.ActionEvent;ImportJava.awt.event.ActionListener;ImportJavax.swing.JButton;ImportJavax.swing.JFrame;ImportJavax.swing.JLabel;ImportJavax.swing.JPanel;ImportJavax.swing.JTextField; Public classLeapyearextendsJFrameImplementsactionlistener{PrivateJTextField textfield=NULL; PrivateJButton btn; Publicleapyear () {JFrame F=NewJFrame ("Leap year"); JPanel P=NewJPanel (); TextField=NewJTextField ("", 10); JButton btn=NewJButton ("OK"); JLabel Label1=NewJLabel ("Input"); Btn.addactionlistener ( This); P.add (Label1); P.add (TextField); P.add (BTN); F.add (P); F.setvisible (true); F.setdefaultcloseoperation (Jframe.exit_on_close); F.setsize (300, 200); F.setbounds (150,150,150,150); F.pack (); } Public voidactionperformed (ActionEvent e) {String F; F=Textfield.gettext (); String Q=""; Try{ intP1 =Integer.parseint (f); if(Checkleap (p1)) {Q= "This is a leap year!"; } Else{Q= "This is not a leap year!"; } } Catch(NumberFormatException s) {Q= "Illegal input!"; } textfield.settext (q); } PublicBoolean Checkleap (intYear ) {Boolean temp=false; if(year% 4 = = 0) {Temp=true; } if(year% 100 = = 0) {Temp=false; } if(Year% 400 = = 0) {Temp=true; } returntemp; } Public Static voidMain (string[] args) {Newleapyear (); } }
The code's algorithm is simple to understand, in the restriction illegal operation, I use the Try,catch method to determine whether the input is a number, if not the number then obtains an error message.
Test Cases
Test Cases |
Expected output |
Actual output |
1234 |
This is not a leap year! |
This is not a leap year! |
2000 |
This is a leap year! |
This is a leap year! |
1000 |
This is not a leap year! |
This is not a leap year! |
Abcd |
Illegal input! |
Illegal input! |
#¥& |
Illegal input! |
Illegal input! |
Test
Java Leap Year test and resolve illegal input