有关测试输入是否是闰年的问题及程序

输入

输入一段字符(正确为数字有可能出现其他字母,符号等非法字符)

输出

提示所输入是否为闰年,如果输入不是数字则提示输入不合法。

闰年的定义

能被4整除但不能被100整除,或者能被400整除的。

测试用例

编号 输入 预计输出
1 400
2 1000
3 10/*0 非法

测试截图:

代码:

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.text.Text;
import javafx.stage.Stage;


public class Run_nian extends Application {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Run_nian.launch(args);

	}

	@Override
	public void start(Stage stage) throws Exception {
		// TODO Auto-generated method stub
		AnchorPane root = new AnchorPane();
		Text nian = new Text("Year:");
		AnchorPane.setLeftAnchor(nian, 10.0);
		AnchorPane.setTopAnchor(nian, 10.0);
		final TextField field = new TextField();
		AnchorPane.setTopAnchor(field,10.0);
		AnchorPane.setLeftAnchor(field, 50.0);
		Button but = new Button("ok");
		AnchorPane.setTopAnchor(but, 50.0);
		AnchorPane.setLeftAnchor(but, 100.0);
		but.setOnAction(new EventHandler<ActionEvent>(){
			
			public void handle(ActionEvent event){
				String out = new String("输入不是闰年");
				
				try{
					int year = Integer.parseInt(field.getText());
					if(year%400==0||(year%4==0&&year%100!=0)){
						out  = "输入是闰年";
					}
				}
				catch(Exception e){
					out = "输入不合法";
				}

				System.out.println(out);
			}
		});
		root.getChildren().addAll(nian,field,but);
		stage.setScene(new Scene(root,250,100));
		stage.show();
		
	}

}

对于Integer.parseInt(String)的报错问题

若不适用try catch 的异常解决方法,直接使用 Integer.parseInt()会报错,如下

该错误是由于本函数是将字符串参数作为带符号十进制整数来分析。除过第一个字符为 ASCII 字符中减号 '-' 表示的负数,字符串中的字符都必须是十进制数。

原文地址:https://www.cnblogs.com/lxm27/p/4396924.html