新手学jsp,内嵌的java代码不知道出什么问题了,大家帮我看看,程序爆出integer.parseint()得到空值。。

<%@page contentType="text/html;charset=GB2312"%>
<html>
<h1>我的计算器</h1>
<hr>
<head>

<script language="javascript">

function checknum(){
if(form1.num1.value==""){
window.alert("不能为空。。。");
return false;
}
if(form1.num2.value==""){
window.alert("不能为空。。。。");
return false;
}
if(Math.round(form1.num1.value)!=form1.num1.value){
window.alert("不是数字。。。。");
return false;
}
if(Math.round(form1.num2.value)!=form1.num2.value){
window.alert("不是数字。。。。");
return false;
}
if(form1.st.value=="/"){
if(form1.num2.value=="0"){
window.alert("不能为0.。。。");
return false;
}
}
}

</script>
</head>

<body>

<form name="form1" action="myCal.jsp">
请输入第一个数<input type="text" name="num1" ><br>
<select name ="st">
<option value="+">+</option>
<option value="-">-</option>
<option value="*">*</option>
<option value="/">/</option>
</select><br>
请输入第一个数<input type="text" name="num2" ><br>
<input type="submit" value="submit" onclick="return checknum()">
</form>
<%
String num1=request.getParameter("num1");
String num2=request.getParameter("num2");
String st=request.getParameter("st");
int n1=Integer.parseInt(num1);
int n2=Integer.parseInt(num2);
int result=0;
if(st.equals("+")){
result=n1+n2;
}else if(st.equals("-")){
result=n1-n2;
}else if(st.equals("*")){
result=n1*n2;
}else{
result=n1/n2;
}
%>
<hr>
计算结果: <%=result %>
</body>
</html>

我演示了一遍,如果你输入的num1 num2都是数字,没有你所说的那种情况(即程序爆出integer.parseint()得到空值,你可以看看页面跳转的是否正常,正确的应该是http://localhost:8080/****/myCal.jsp?num1=1&st=+&num2=2(假设你输入的值是1和2,选的运算符是+)。如果你输入的num1或num2有不是数字的,程序会报NumberFormatException,因为if(Math.round(form1.num2.value)!=form1.num2.value){
window.alert("不是数字。。。。");
return false;
}
写的有错误,你可以参考api帮助文档,看看Math.round函数的用法。
希望对你有所帮助。
温馨提示:答案为网友推荐,仅供参考
第1个回答  2010-04-12
下面不对
if(Math.round(form1.num1.value)!=form1.num1.value){
window.alert("不是数字。。。。");
return false;
}
if(Math.round(form1.num2.value)!=form1.num2.value){
window.alert("不是数字。。。。");
return false;
}
要将其强转:
int(form1.num1.value)
int(form1.num2.value)
第2个回答  2010-04-12
试试checknum(){
****
****
****
return true;
}
就不报空了,因为你没有成功提交
相似回答