Reputation: 53
How would I go about creating a unique object every time a user wants to create a new account?
For example if user makes an account I would like an object named acc1 then if a user makes another account i would like the object named acc2.
Account ac = new Account(input.nextInt(),0,0);
. This is around where i need it to happen.
I tried keeping the code as simplistic as possible and also note I'm rather new to java and this is a personal project just to learn.
System.out.println("Welcome to JAVA Bank");
System.out.println("____________________");
System.out.println("Plese Choose an Option: ");
System.out.println("");
System.out.println("(1) New Account");
System.out.println("(2) Enter Existing Account");
int choice = input.nextInt();
switch(choice){
case 1:
System.out.println("Please choose an Account ID#");
Account ac = new Account(input.nextInt(),0,0);
break;
public class Account {
private int id = 0;
private double balance = 0;
private double annualInterestRate = 0;
private Date dateCreated;
public Account(int id, double balance, double annualInterestRate) {
this.id = id;
this.balance = balance;
this.annualInterestRate = annualInterestRate;
this.dateCreated = new Date();
}
Help is appreciated thank you.
Upvotes: 4
Views: 1772
Reputation: 914
If you are wanting a unique way of identifying multiple Accounts perhaps a HashMap is the way to go. A HashMap stores key-value pairs where each key is unique.
Create a class level variable to store the accounts:
Map<String, Account> accounts = new HashMap<String, Account>();
Create/Add account to HashMap:
case 1:
System.out.println("Please choose an Account ID#");
int accountID = input.nextInt(); //Get the requested ID
if (accounts.containsKey("acc"+accountID) //Check to see if an account already has this ID (I added acc to the start of each account but it is optional)
{
//Tell user the account ID is in use already and then stop
System.out.println("Account: " + accountID + " already exists!");
break;
}
//Create account and add it to the HashMap using the unique identifier key
Account ac = new Account(input.nextInt(),0,0);
accounts.put("acc"+accountID, ac);
Upvotes: 4