闰年测试中的非法输入
一、问题描述
本篇博客讲解的是一个关于闰年测试的例子,首先科普一下什么是闰年?
闰年(Leap Year)是为了弥补因人为历法规定造成的年度天数与地球实际公转周期的时间差而设立的。补上时间差的年份为闰年。闰年包括在公历(格里历)或夏历中有闰日的年份。闰年有366天。(出自百度百科)
闰年的判定方法:
1、普通年能被4整除且不能被100整除的为闰年。(如2004年就是闰年,1900年不是闰年)
2、世纪年能被400整除的是闰年。(如2000年是闰年,1900年不是闰年)
正常情况下在文本框内输入一个年份,点击OK按钮,程序会判定出该年份是否问闰年,但是如果输入的是一个字符串或者是一个负数,程序就会产生异常,而本篇博客就是为了解决这一问题。
二、代码实现
采用javascript来验证文本框中的年份是否为闰年,同时使用try、catch来解决输入异常问题。蓝色部分为核心代码。
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<center>
<p>请输入年份来鉴定是否为闰年。</p>
<input id="demo" type="text">
<script>
function myFunction()
{
try
{
var x=document.getElementById("demo").value;
if(isNaN(x)) throw "not a number";
else{
if(x<0) throw "not a positive number";
else{
if((x%400==0)||(x%4==0&&x%100!=0))
alert("是闰年");
else
alert("不是闰年");
}
}
}
catch(err)
{
alert(err);
}
}
</script>
<button type="button" οnclick="myFunction()">OK</button>
</center>
</body>
</html>
三、测试用例
编号 |
输入 |
预期输出 |
1 |
2008 |
是闰年 |
2 |
2000 |
是闰年 |
3 |
2003 |
不是闰年 |
4 |
abcd |
not a number |
5 |
-1 |
not a positive number |
四、测试结果图