日期:2014-05-17  浏览次数:20696 次

奇怪的java 奇怪的字符问题
代码如下
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletExceptionIOException {
User user = new User();
response.setContentType("text/html;charset=gb2312");
PrintWriter out = response.getWriter();
String sName = request.getParameter("username");
String sPassword = request.getParameter("password");
String sRepassword = request.getParameter("repassword");
String sSex = "1";
String snickName = request.getParameter("nickname");
if(sName==null){
//姓名不能为空
out.println("<h3>姓名不能为空</h3>");
return;
}
if(sPassword==null){
//密码不能为空
out.println("<h3>密码不能为空</h3>");
return;
}
if(sRepassword==null){
//确认密码不能空
out.println("<h3>确认密码不能空</h3>");
return;
}
/*if(sSex==null){
//性别不能为空
return;
}*/
if(sPassword!=sRepassword){
//两次输入密码不一致
out.println("<h3>两次输入密码不一致</h3>");
return;
}
if(user.checkUser(sName))
{
//用户名已经被占用
out.println("<h3>用户名已经被占用</h3>");
return;
}
if(user.doUserRegister(sName, sPassword, sSex, snickName)){
//注册成功!
out.println("<h3>注册成功!</h3>");
}
else{
//注册失败!
out.println("<h3>注册失败!</h3>");
}
}
静态页面就不用写了传递的参数也都传递过来了 ,现在是我传的是两个密码
一个是Password=1&rpassword=1
可是在判断的时候sPassword!=sRepassword返回值是true 好不明白为什么呢?
java

------解决方案--------------------
判断是否相等的时候用
!sPassword.equal(sRepassword)

sPassword!=sRepassword是判断的两个变量的内存地址
------解决方案--------------------
sPassword!=sRepassword都是string类型,就不要用!=比较大小。
------解决方案--------------------
引用:
字符串不是变量吗?好纠结啊 如果是对象我还知道用equal方法可是字符串这个东东还是有点糊涂


JAVA里所有的东西都是对象,没有变量,旧版本中还有原始类型是非对象的,
但是加了自动装箱拆箱后,所有原始类型都被自动装箱成对象了。

JAVA的字符串也是对象。关于用 == 还是 equal ,没有一定之规,
完全看你要比较的是对象引用的值(用C的术语来说就是指向对象的指针),还是要比较的是是对象的特性值。
如果是判断是否是指向同一对象的指针,就用 == 
如果是判断两个对象的特性值是否一样,就用equals(或者自己实现的compareTo)

如果看一下String的equals的源码,第一行就是用 == 比较是否是同一个对象,如果是同一个对象就直接返回true,因为自己和自己比的话,同一个对象的值总是相等的:
    /**
     * Compares this string to the specified object.  The result is {@code
     * true} if and only if the argument is not {@code null} and is a {@code
     * String} object that represents the same sequence of characters as this
     * object.
     *
     * @param  anObject
     *         The object to compare this {@code String} against
     *
     * @return  {@code true} if the given object represents a