+ 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.
9 Answers
+ 3
Maddie I have made this small example. Hope this helps you.
https://code.sololearn.com/c12ykfHi6EnI/?ref=app
+ 6
Insert the code in question so that we can provide better help
+ 3
Maddie Using your code I implemented a void printWallet() method.
https://code.sololearn.com/cqODBdGVOb89/?ref=app
+ 2
Maddie You do not need the class wallet, but maybe a good exercise to use it.
+ 1
thank you! So i guess I don’t need a wallet class...
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
}
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 + ")";
}
}
0
how can i get the Wallet to print out its contents?
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



