Search code examples
javaclasshashmap

Accessing Map from another class not working


I'm making a banking system simulator, with 2 classes- signup and login.

public class Signup {
    Scanner scanner = new Scanner(System.in);
    public Map<String,String> account = new HashMap<>();
    String input_username;
    String input_password;

    public Map<String,String> getAccount() {
        for (String username : account.keySet()) {
            System.out.println(username);
        }
        return account;
    }

    public void signup() {
        System.out.println("Enter username: (Signup)"); //add: verify only 1 account exists
        input_username = scanner.next();
        System.out.println("Enter password:");
        input_password = scanner.next();
        System.out.println("Signup successful.");
        account.put(input_username,input_password);
    }
}

The signup class saves usernames and passwords in the account hashmap, which gets used by the login class:

public class Login {
    Scanner scanner = new Scanner(System.in);
    Signup getDetails = new Signup();
    public Map<String,String> account = new HashMap<>();

    public void login() {
        account = getDetails.getAccount();
        for (String username : account.keySet()) {
            System.out.println(username);
        }
        System.out.println("Enter username (Login)");
        if (account.containsKey(scanner.next())) {
            System.out.println("Enter password");
        } else {
            System.out.println("This account isn't registered.");
        }
    }
}

(The for loop is just used to verify if usernames are saved inside hashmap.

However, when I use the getDetails function to access it from signup class, it doesn't work. The for loop doesn't output anything.


Solution

  • how do you create your objects?

    The moment your Login class gets created, you create a new Signup object with an empty HashMap. So if you at first create your Signup object, then

    You have different options, one example is to create a third class as a MemberSafe (or something like that) and give this exact object into the constructor of your Login and Signup and refer to it as a storage, like:

    public static void main(String[] args) {
    
        MemberSafe memberSafe = new MemberSafe();
        
        Signup signup = new Signup(memberSafe);
        Login login = new Login(memberSafe);
    }
    

    whats also possible is, that you make your accounts map static inside of the Signup class (I would not prefer that, but its up to you I guess).

    Also I wouldn't create a duplicate Map inside of the Login class

    Best regards, Julius