闰年检测问题

关于闰年测试的问题:

条件:1. 4 年一闰, 100 年不闰,400年又闰。

   2. 输入年份大于0。

   3. 输入只能为数字。

源代码:

public class leapyear extends Application {

public static void main(String[] args) {
leapyear.launch( args );
}

private TextField textfield = new TextField();

@Override
public void start(Stage arg0) throws Exception {
arg0.setTitle( "LeapYear" );

HBox hbox = new HBox( 8 );
textfield.setPrefColumnCount( 25 );
hbox.setAlignment( Pos.CENTER_LEFT );
Button btn = new Button();
btn.setText( "确定" );
btn.setOnAction( new Listener() );
hbox.getChildren().addAll( new Label( " 请输入年份: "), textfield, btn );

arg0.setScene( new Scene( hbox, 450, 80 ));
arg0.show();
}

public class Listener implements EventHandler<ActionEvent> {

@Override
public void handle(ActionEvent arg0) {
String str = textfield.getText();
String inf = "";
if( isLeapYear( Integer.parseInt( str ) ) ) {
inf = "闰年";
}
else {
inf = "非闰年";
}
JOptionPane.showMessageDialog( null, inf, "information",
JOptionPane.INFORMATION_MESSAGE );
}
}

private boolean isLeapYear( int year ) {
if( year % 4 != 0 ) {
return false;
}
else if( year % 100 != 0 ) {
return true;
}
else if( year % 400 != 0 ) {
return false;
}
else {
return true;
}
}
}

编号 测试用例 结果
1 1995 非闰年
2 2000 闰年
3 2012 闰年
4 0000 闰年
5 1900 非闰年

测试结果:

1.

2.

3.

4.

5.

但以上出现了一个问题,当输入为空时,错误。还有当输入飞数字的时候也会显示错误。

原文地址:https://www.cnblogs.com/HCS1995/p/4398634.html