Reputation: 119
So right now, I am making a simple java banking program. It allows you to add a customer and deposit/withdraw funds. Right now, I have 3 classes: Main, Bank, and Customer. Right now I have it so that when you add a customer, it asks you for a name. But right now I am having trouble naming them. I want Customer to have a username as the object name. For example, if I typed in Bob1789 as the username, the program would do:
Customer Bob1789 = new Customer("Bob1789");
If I typed in randomcustomer123 the program would do:
Customer randomcustomer123 = new Customer("randomcustomer123");
So basically, whatever I type in the box from the scanner, to be passed to the Customer name.
Customer (whatever was typed in the scanner) = new Customer((whatever was typed in the scanner));
I have tried to do this, but java always assumes that the scanner.NextLine() is the Object name.
Is there any way to do this?
Upvotes: 3
Views: 80
Reputation: 2751
Don't know why you want to use obj name. Probably you need to use HashMap<String, Customer>
where name is the key and value is the object.
Map<String, Customer> map = new HashMap<>();
to add map.put("yourName", obj);
to fetch map.pget("yourName");
Upvotes: 2
Reputation: 270995
You can use a HashMap<String, Customer>
for this. This allows you to store name-customer pairs.
HashMap<String, Customer> allCustomers = new HashMap<>();
To create a new customer and put it into the map,
String customerName = scanner.nextLine();
allCustomers.put(customerName, new Customer(customerName));
To get a customer with a specific name, use this:
allCustomers.get("some name");
Upvotes: 3