比较使用参数的对象时总是返回错误
问题描述:
我不知道为什么与使用该参数的帐户进行比较时总是返回false。它只有在帐号被硬编码时才会返回true。比较使用参数的对象时总是返回错误
public class Account
{
public Account(String username, String password, String lastname, String firstname){
this.username = username;
this.password = password;
this.firstname = firstname;
this.lastname = lastname;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
public String getFirstname() {
return firstname;
}
public String getLastname() {
return lastname;
}
private String username;
private String password;
private String firstname;
private String lastname;
public boolean equals(Object obj)
{
boolean result = false;
if (obj != null && obj instanceof Account)
{
Account p = (Account)obj;
if (getUsername().equals(p.getUsername())
&& getPassword() == p.getPassword())
{
result = true;
}
}
return result;
}
}
我的servlet
Set<Account> acc = new HashSet<Account>();
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
acc.add(new Account("test1", "pass123", "Boom", "Bang"));
acc.add(new Account("test2", "pass123", "Beam", "Beng"));
PrintWriter out = response.getWriter();
String username = "";
String password = "";
if(request.getParameter("Username") != null){
username = request.getParameter("Username");
}
if(request.getParameter("Password") != null){
password = request.getParameter("Password");
}
Account act1 = new Account(username, password, "", "","");
System.out.print(username+password); // test if the username and password change based on the parameter
/*
Works only on hard code
Account act1 = new Account("test1", "pass123", "", "","");
*/
out.print("<html>");
out.print("<head><link href='layoutit/css/bootstrap.min.css' rel='stylesheet'>"
+ "<link href='layoutit/css/style.css' rel='stylesheet'>");
out.print("<title></title>");
out.print("</head>");
out.print("<body");
if(acc.contains(act1)){ // the condition that always return false if not hardcode
out.print("<h3>Click <a href='displayuser.html'>here</a> to continue.</h3>");
}
else
out.print("<h1>Invalid user account entered.Click <a href='index.html'>here</a> to login.</h1>");
out.print("</body>");
out.print("</hmtl>");
out.close();
}
答
比较密码时使用.equals
,而不是==
。
答
密码也是字符串(从我对这个问题的评论复制),但使用的是==
比较它,使用.equals
。使用它,如下所示,从下:当您使用instanceof
操作
if (getUsername().equals(p.getUsername())
&& getPassword() == p.getPassword())
要
if (getUsername().equals(p.getUsername())
&& getPassword().equals(p.getPassword()))
而且,不需要单独的空检查。
所以,你可以在此线
if (obj != null && obj instanceof Account)
为
if (obj instanceof Account)
如果使用.equals代替==用于比较的密码是否行得通? – immibis
感谢它的工作。我错过了。 :) –
因此在这里接受正确的答案... –