软件测试-4 判断闰年的程序以及防止输入非法字符

一、题目

判断所输入的年份是否是闰年

二、程序实现

我继续使用javascript+HTML来实现:

不考虑异常的输入,判断闰年的程序如下:

function isLeapYear( y ){
    return ( y % 400 == 0 ) || ( y % 4 == 0 && y % 100 != 0 );
}

但是在实际使用时必须考虑是否有异常输入,所以我可以在调用该函数前检测一下输入,保证输入是合法的:

function isInt(input){
    var reg = /^[0-9]+$/;
    if( reg.test( input ) )
        return true;
    return false;
}

每次判断前使用isInt()函数 保证其输入合法:

function check(){
    var input = document.getElementById("year").value;
    if( isInt(input) ){
        if( isLeapYear(input) ) alert("是闰年");
        else alert("不是闰年");
    }
    else alert("输入不合法!");
}

点击此处访问该程序:http://zhaobi.org/softwaretest/Test3.html

三、测试

 测试用例:

输入 预期输出
2400 yes
1900 no
2004 yes
2015 no
adc Exception
空输入 Exception

测试:

四、源代码

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>EditBox</title>
</head>
<body>
<div style="220px">
请输入年份:<input type="text" id="year"/><br>
<input type="button" value="OK" onClick="check()"/>
<script type="text/javascript">

function isInt(input){
    var reg = /^[0-9]+$/;
    if( reg.test( input ) )
        return true;
    return false;
}

function isLeapYear( y ){
    return ( y % 400 == 0 ) || ( y % 4 == 0 && y % 100 != 0 );
}

function check(){
    var input = document.getElementById("year").value;
    if( isInt(input) ){
        if( isLeapYear(input) ) alert("是闰年");
        else alert("不是闰年");
    }
    else alert("输入不合法!");
}

</script>
</div>
</body>
</html>

五、总结

其实也可以将检测输入的代码段合并到isLeapYear()函数中,这样可以减少函数的数量。

原文地址:https://www.cnblogs.com/b-sir/p/4396403.html