通过字符的ASCII在、码值来判断是否为数字,首先将整个字符串通过String类的toCharArray()方法转换为字符串数组,判断每个字符的ASCII值是否在4-57之间,满足条件使用StringBuffer对象累加每个字符,最后判断StringBuffer对象的字符长度是否等于字符数组的长度,若相等则说明为数字
创建StringUtil的JavaBean类,验证字符串是否为数字
public class StringUtil5 {
private String numStr; //要判断的字符串
private boolean number; //判断结果
private String cue; //提示信息
public String getnumStr() {
return numStr;
}
public void setnumStr(String numStr) {
numStr=numStr.replaceAll(" ","");
this.numStr = numStr;
}
public boolean isNumber() {
char cArr[]=numStr.toCharArray(); //将字符串转换为字符数组
StringBuffer sb=new StringBuffer("");//创建动态字符串对象
for(int i=0;i<cArr.length;i++){
int ascii=(int)cArr[i]; //将字符串强制转换为int值,该值为字符的ASCII码
if(ascii>=48&&ascii<=57){ // 数字0-9的ASCII码范围在48-57之间
sb.append(cArr[i]); //条件满足,将字符添加到StringBuffer字符串末尾
}
}
if(sb.length()==cArr.length){
number=true;
this.setCue("您输入的是数字!");
}else{
number=false;
this.setCue("您输入的不是数字!");
}
return number;
}
public void setNumber(boolean number) {
this.number = number;
}
public String getCue() {
return cue;
}
public void setCue(String cue) {
this.cue = cue;
}
}
创建index.jsp页面,输入表单信息
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="check5.jsp" method="post">
<table>
<tr>
<td align="right">月工资收入:</td>
<td><input type="text" name="numstr">元</td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="验证"></td>
</tr>
</table>
</form>
</body>
</html>
创建check.jsp页面,判断
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
String numStr=request.getParameter("numstr");
%>
<jsp:useBean id="strBean" class="com.cn.zj.bean.StringUtil5"></jsp:useBean>
<jsp:setProperty property="numStr" name="strBean" value="<%=numStr %>"/>
<table>
<tr>
<td align="right">输入的字符串为:</td>
<td>
<jsp:getProperty property="numStr" name="strBean"/>
</td>
</tr>
<tr>
<td align="right">是否为数字:</td>
<td>
<jsp:getProperty property="number" name="strBean"/>
</td>
</tr>
<tr>
<td align="right">提示信息:</td>
<td>
<jsp:getProperty property="cue" name="strBean"/>
</td>
</tr>
</table>
</body>
</html>