Kevin Zaki
Kevin Zaki

Reputation: 146

using a String variable to access an object in a class

I am fairly new to JAVA, but I am working on a program and this is the issue im running into, might be a simple fix.

I prompt the user to enter their ID for a mock ATM system.

            {
            System.out.println("Enter an ID: ");
            Scanner input = new Scanner(System.in);
            String acctID = input.next();
            withdrawAccount(acctID);
            System.out.println(IDnum.getBalance());
            }

There is more to the code but it is irrelevant at this time. There will be several if statements to see what action the user wants to do, i.e. withdraw money from their account. In this program I want to have the user enter there ID and save it as a string and pass it to WithdrawAccount method. So acctID would reference what ever the user enters for the account ID. Note the account ID is the same as the name of the Account variable. so Account 0 will have an ID of 0.

    public static void withdrawAccount(String acctID)
            {
            System.out.println("Enter Withdraw Amount: ");
            Scanner input = new Scanner(System.in);
            double WithdrawAmount = input.nextDouble();
            acctID.setBalance(acctID.getBalance() - WithdrawAmount);
            }

Upvotes: 2

Views: 94

Answers (2)

JB Nizet
JB Nizet

Reputation: 692231

If I understand your question correctly, you want to associate String IDs with accounts identified by these IDs. One way to do that is to use a Map:

private Map<String, Account> accountsById = new HashMap<String, Account>();

...

accountsById.put("1", account1);
accountsById.put("2", account2);
accountsById.put("3", account3);
...

And then to get the account with a given ID:

Account account = accountsById.get(idEnteredByTheUser);

Upvotes: 1

Wald
Wald

Reputation: 1091

Probably storing them into an ArrayList or Map would best to save them.

And when you are calling the withdraw method you will need to pass the whole 'Account' instead of a string so you can edit exactly their balance with the 'setBalance' method of the class.

Upvotes: 0

Related Questions