<%
String UserName= " ";String UserText= " ";
UserName=request.getParameter( "name ");
UserText=request.getParameter( "text ");
if(UserName.length()!=0 && UserText.length()!=0)
{}
%>
上面是程序中一段代码,发生空指针异常NullPointerException
我删了if(UserName.length()!=0 && UserText.length()!=0){}或是删了UserName=request.getParameter( "name ");
UserText=request.getParameter( "text ");
都不发生异常了,为什么会发生这种情况?请指点
------解决方案--------------------
你在URL后面加入name和text请求参数就不会了
因为UserName=request.getParameter( "name ");
UserText=request.getParameter( "text ");
当你没有这两个请求参数的话userName,UserText就会变为null,也就是无实例对象,从而你调用if(UserName.length()!=0 && UserText.length()!=0){}它就会抛出异常,
而当你删除UserName=request.getParameter( "name ");
UserText=request.getParameter( "text ");
因为你前面有String UserName= " ";String UserText= " ";也就是实例化了二个空字符串,所以你再调用if(UserName.length()!=0 && UserText.length()!=0){}就不会抛出异常
------解决方案--------------------
<%
String UserName= " ";String UserText= " ";
UserName=request.getParameter( "name ");
UserText=request.getParameter( "text ");
if(UserName.length()!=0 && UserText.length()!=0)
{}
%>
改成
if(UserName!=null&&UserName.length()!=0 &&UserText!=null&& UserText.length()!=0)
{}
就没有事情啦,因为你的UserName是空的,所以调用length()方法就有错误了