比较用户输入与getter

时间:2017-03-23 11:20:36

标签: java

我正在尝试比较用户输入'username'以获取买方类'Buyer.getUser'中的方法,并将'password'与买方类'Buyer.getPass'中的方法进行比较 它一直要求我在买方类中将用户名和密码设置为静态,但即使输入了正确的输入,这仍然总是表示登录不成功。

用户类

switch (credentials) {
        case 1 : {
            System.out.println("Buyer");
            System.out.println("Enter Username: ");
            username = S.next();
            System.out.println("Enter Password: ");
            password = S.next();

                            if ((username.equals(Buyer.getUser())) && (password.equals(Buyer.getPass()))){
                                System.out.println("Login Successful");
                            }else{ 
                                System.out.println("Login unsucessful");
            break;
        }
                    }

买方类

public class Buyer {

private String username;
private String password; 


public Buyer (String username, String password){
    this.username = username;
    this.password = password;
}

public String getUser(){
    return username;
}

public String getPass(){
    return password;
}

用户类

public static void buyerCredentials() {
    ArrayList<Buyer> buyer = new ArrayList<Buyer>();

    buyer.add(new Buyer("user1", "pass123"));
    buyer.add(new Buyer("user2", "pass321"));

    for (int i = 0; i < buyer.size(); i++){
        System.out.println(buyer.get(i));
    }
}

提前致谢!

2 个答案:

答案 0 :(得分:1)

实际上你并没有创建Buyer类的对象,而是将对象调用为静态引用而不是对象,所以你总是得到null用户名和密码。

Buyer buyer = new Buyer();
buyer.getUser();
buyer.getPass();

答案 1 :(得分:0)

在比较之前,您必须创建一个Buyer对象的实例。

Buyer myBuyerInst = new Buyer("MyUser", "MyPass");

现在你可以比较:

username.equals(myBuyerInst.getUser()) 

您必须遍历列表:

for(Buyer b : buyer) {
    username.equals(b.getUser()) 
}