+ 1

ArrayLists!

In my Wallet class I have an arraylist called wallet of type Coin (i have a Coin class too, a coin has a name and a value). How can I override the toString method so that the values from the wallet array list are displayed instead of the address of the list (gibberish). The program is in java.

8th Apr 2019, 11:34 AM
Maddie
Maddie  - avatar
9 Answers
+ 3
Maddie I have made this small example. Hope this helps you. https://code.sololearn.com/c12ykfHi6EnI/?ref=app
8th Apr 2019, 10:40 PM
Denise Roßberg
Denise Roßberg - avatar
+ 6
Insert the code in question so that we can provide better help
8th Apr 2019, 11:56 AM
Saksham Jain
Saksham Jain - avatar
+ 3
Maddie Using your code I implemented a void printWallet() method. https://code.sololearn.com/cqODBdGVOb89/?ref=app
9th Apr 2019, 12:03 AM
Denise Roßberg
Denise Roßberg - avatar
+ 2
Maddie You do not need the class wallet, but maybe a good exercise to use it.
8th Apr 2019, 11:11 PM
Denise Roßberg
Denise Roßberg - avatar
+ 1
thank you! So i guess I don’t need a wallet class...
8th Apr 2019, 10:56 PM
Maddie
Maddie  - avatar
0
You are so near to the answer. Just override the toString method of class Coin Add this to your class Coin @Override public String toString() { return "A coin"; //or return a modified string with a meaningful name }
8th Apr 2019, 1:31 PM
Seniru
Seniru - avatar
0
import java.util.ArrayList; public class Wallet { private ArrayList<Coin> wallet; public Wallet() { wallet = new ArrayList<Coin>(); } public void addCoin(Coin newCoin) { wallet.add(newCoin); } public double getTotal() { double total = 0; for (Coin c: wallet) { total += c.getValue(); } return total; } public void removeCoin(Coin targetCoin) { boolean targetFound = false; for(int i = 0; i < wallet.size(); i++) { while(targetFound == false) { if(wallet.get(i).equals(targetCoin)) { wallet.remove(i); targetFound = true; } } } } public String getString() { } } public class Coin { private double value; private String name; public Coin(double coinValue, String coinName) { value = coinValue; name = coinName; } public double getValue() { return value; } public String getName() { return name; } public String toString() { return name + " (value = " + value + ")"; } }
8th Apr 2019, 5:37 PM
Maddie
Maddie  - avatar
0
how can i get the Wallet to print out its contents?
8th Apr 2019, 5:38 PM
Maddie
Maddie  - avatar
0
if i were to use it (wallet class), how could i print the contents of the array it adds to? in the code i have above
8th Apr 2019, 11:26 PM
Maddie
Maddie  - avatar