0

I have an ArrayList of accounts containing the attributes accountNumber, accountHolder, and balance. Previously, my method would take the name of the object as an argument. For the purpose of preventing user error, I would like my program to create a new object upon calling a method and automatically name that object based on how many objects are already existing in my ArrayList. The issue I am running into (I think) is the fact that I can not convert a string into an object.

public void addAccount(String newAccountNumber, String newAccountHolder, double newStartingBalance)
    {
        String newAccountName = "account" + accounts.size() + 1;
        accounts.add(newAccountName);
        int x = accounts.indexOf(newAccountName);
        accounts.get(x).setAccountNumber(newAccountNumber);
        accounts.get(x).setAccountHolder(newAccountHolder);
        accounts.get(x).setBalance(newStartingBalance);
    }
  • 1
    What does `+` mean in the context of `"a" + "b"`? What does `+` mean in the context of `1 + 2`? – srk Apr 01 '21 at 20:09
  • I'm trying to create a string "account" + the number of existing accounts + 1, so that if I want to make my first account, it is automatically assigned the name "account1", then if I make a second account, it will detect that there is already an element in the array, so it would be account + 1 (number of existing account) + 1 (to include the account being added) – James S Apr 01 '21 at 21:02
  • The issue is that the `+` operator means something different for strings (concatenation) vs. numbers (addition). [Does this answer your question?](https://stackoverflow.com/questions/38352779/java-operator-between-arithmetic-add-string-concatenation) – srk Apr 02 '21 at 01:09
  • @JamesS Try this and see if it gets your desired output: `String newAccountName = "account" + String.valueOf((accounts.size() + 1));` – Mohit Dodhia Apr 02 '21 at 06:31

0 Answers0