1

I have a banking program with an enter customer, and balance method. The method adds a String and a double to my accounts ArrayList, if the name Sam for example is inputted, I want to stop that name from being inputted again, as currently it creates two separate Strings and balances for Sam and when withdrawing/depositing both are modified since I check the name/String to get the right account.

class Bank {

ArrayList<Account> accounts = new ArrayList<Account>();

public void enterCustomers() {
    String name = "";
    double balance;
    System.out.println("Enter customer names or q to quit entering names");
    while (true) {
        name = MyConsole.getString("Enter a customer name: ");
        if (name.equals("q")) {
            break;
        }
        balance = MyConsole.getDouble("Enter opening balance: ");
        accounts.add(new Account(name, balance));
    }
}
Sam Black
  • 93
  • 1
  • 6
  • 3
    consider using a `map` – Scary Wombat Sep 20 '18 at 06:42
  • 2
    or, if you do want to use a List, the .contains(Object o) method will do wonders – Stultuske Sep 20 '18 at 06:43
  • 1
    You can use streams to filter out list and check if same name already exists – Jignesh M. Khatri Sep 20 '18 at 06:43
  • 2
    @Stultuske `Account.equals` may need some work – Scary Wombat Sep 20 '18 at 06:44
  • 1
    simple solution: scan the list for an account with the given name. Can use streams, as already proposed, or a bit simpler, a fore loop like `for (Account acc : accounts) { if (acc.getName().equals(name)) { /* errormessage */; continue;} }` (and, if order is **not** important, consider using `HashSet`/`Set` instead of lists. I would also suggest, as Scary Wormbat did, to add an `equals` method to the Account, since accounts with the same name should be considered as being equal (id would be better in production) – user85421 Sep 20 '18 at 06:59
  • @ScaryWombat not only `Account.equals`, but also `Account.hashCode` as well. If override equals has to override hashCode as well. – Awan Biru Sep 20 '18 at 07:20
  • for learning you could also use/check `list.iterator()`, see [documentation](https://docs.oracle.com/javase/10/docs/api/java/util/List.html#iterator()) - what we had to use before we got the for-each loops. And please check the implementation of `equals` as suggested by others (special Sweeper's answer) - understanding equals and hashcode is importatnt (essential)! – user85421 Sep 20 '18 at 07:21
  • @ScaryWombat possible, but I won't guess on that based on the current shown code – Stultuske Sep 20 '18 at 07:55

5 Answers5

3

There are many ways of doing this. Here's a way that requires the least modification to your existing code that I can think of:

name = MyConsole.getString("Enter a customer name: ");
if (name.equals("q")) {
    break;
}
if (accounts.stream().anyMatch(x -> x.getName().equals(name))) {
    System.out.println("This name already exists!"); 
    continue;
}
balance = MyConsole.getDouble("Enter opening balance: ");
accounts.add(new Account(name, balance));

Alternatively, override equals and hashCode in Account, and store them in a HashSet<Account>. You can then check whether something is already in the set at a lower time complexity.

// in your Account class
@Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;

    Account account = (Account) o;

    return name.equals(account.name);

}

@Override
public int hashCode() {
    return name.hashCode();
}

// in Bank class
HashSet<Account> accounts = new HashSet<>();

public void enterCustomers() {
    String name = "";
    double balance;
    System.out.println("Enter customer names or q to quit entering names");
    while (true) {
        name = MyConsole.getString("Enter a customer name: ");
        if (name.equals("q")) {
            break;
        }
        balance = MyConsole.getDouble("Enter opening balance: ");
        if (!accounts.add(new Account(name, balance))) {
            System.out.println("This customer already exists!");
        }
    }
}
Sweeper
  • 213,210
  • 22
  • 193
  • 313
2

Are you set on using an Array with Accounts?

Other data structures exist, such as the Set That already filter duplicate entries. Set checks the equals method of the objects being inserted against the elements in the Set. In this case that means you would have to implement an equals method in your Account class, that checks if the names of the account are equal.

Blokje5
  • 4,763
  • 1
  • 20
  • 37
0

With java 8 you can do this

boolean nameExists = accounts.stream().anyMatch(account-> "name".equals(account.getName()));

or another approach would be storing name and balance as key value pairs in HashMap, it has a method containsKey to check for the key existence.

raviraja
  • 676
  • 10
  • 27
0

Thank you everyone for commenting! I should have mentioned I'm in my first semester of computer science so everything's still very new to me, but now I've got some more stuff to study up on haha. I decided to go with the for loop suggested by Carlos for simplicity sake.

        for (Account acc : accounts) { 
            if (acc.getName().equals(name)) { 
                System.out.println("That name already exists, please enter a different one."); 
                continue;
            } 
Sam Black
  • 93
  • 1
  • 6
-1

If you dont want to use duplicate values then go with Set interface which is a part java.util and extends java.util.Collection interface. It does not allow the use of duplicate elements and at max can accommodate only one null element.

For more reference check the following link

Set in java

Akshay kumar
  • 51
  • 1
  • 2