为什么这个.equals()不起作用?

时间:2014-03-05 14:59:40

标签: java android eclipse string equals

我在Eclipse(Android)工作。在以下块中,EmployeeInt和RestaurantInt是数据类型,query()打开与数据库的连接并解析结果。当我打印查询结果时,我得到相同的字符串,但布尔值仍然是假的。我试过修剪弦乐,但这没有帮助。

public boolean verifyEmployee(String email, String password) {
    ArrayList<EmployeeInt> employeeEmailID = query("SELECT employeeID FROM employees WHERE emailAddress = \'"+email+"\'");
    ArrayList<EmployeeInt> employeePasswordID = query("SELECT employeeID FROM employees WHERE password = \'"+password+"\'");
    String stringEmployeeEmailID = employeeEmailID.toString();
    String stringEmployeePasswordID = employeePasswordID.toString();

    if(stringEmployeeEmailID.equals(stringEmployeePasswordID)) {
        return true;
    } else {
        return false;
    }
}

执行上面的命令我是假的,而执行下面的程序段(几乎完全相同)则说明我是真的。

public boolean verifyRestaurant(String email, String password) {
    ArrayList<RestaurantInt> restaurantEmailID = query("SELECT restaurantID FROM restaurants WHERE emailAddress = \'"+email+"\'");
    ArrayList<RestaurantInt> restaurantPasswordID = query("SELECT restaurantID FROM restaurants WHERE password = \'"+password+"\'");
    String stringRestaurantEmailID = restaurantEmailID.toString();
    String stringRestaurantPasswordID = restaurantPasswordID.toString();

    if(stringRestaurantEmailID.equals(stringRestaurantPasswordID)) {
        return true;
    } else {
        return false;
    }
}

任何人都可以指出我的错误吗?

修改

我将其更改为此并且有效:

public boolean verifyEmployee(String email, String password) {
    ArrayList<EmployeeInt> employeeEmailID = query("SELECT * FROM employees WHERE emailAddress = \'"+email+"\'");
    ArrayList<EmployeeInt> employeePasswordID = query("SELECT * FROM employees WHERE password = \'"+password+"\'");
    int intEmployeeEmailID = employeeEmailID.get(0).getID();
    int intEmployeePasswordID = employeePasswordID.get(0).getID();

    if(intEmployeeEmailID==intEmployeePasswordID) {
        return true;
    } else {
        return false;
    }
}

我知道我也可以使用return(条件),但如果登录失败,我想添加一些消息,例如:

System.err.println("email address and password do not correspond");

我没有制作应用程序来发布,它只是用于作业。谢谢你的帮助!

1 个答案:

答案 0 :(得分:1)

您正在toString()上致电ArrayList。两个不同的ArrayList对象将返回两个不同的toString()字符串。您可能想要获取ArrayList的第一个元素,并将THAT转换为字符串。

示例

EmployeeInt是您的自定义对象。在我的示例中,我假设它有一些int字段,可以使用getID()进行检索。

ArrayList<EmployeeInt> idList = query("SELECT employeeID FROM employees WHERE emailAddress = \'"+email+"\'");
int ID = idList.get(0).getID();
stringEmployeeEmailID = String.valueOf(ID);

这可能比代码更容易阅读:

  • query()会返回ArrayList
  • 我们提取ArrayList的第一个元素 - 这是你遗漏的部分
  • 我们获得该元素的ID
  • 我们将其转换为字符串