I'm having a difficult time figuring out a way to convert a array of ints to a String just using String builder. In my toString Method, Am I using the right for loop?
public class Wallet {
// max possible # of banknotes in a wallet
private static final int MAX = 10;
private int contents[];
private int count; // number of banknotes stored in contents[]
public Wallet() {
count = 0;
contents = new int[MAX];
}
public Wallet(int a[]) {
contents = new int[MAX];
for (int i = 0; i < a.length; i++) {
contents[i] = a[i];
count++;
}
}
public String toString() {
StringBuilder builder = new StringBuilder("Wallet[" + contents + "]");
for (int s : contents) {
builder.append(s);
}
return builder.toString();
}
}
Here is the walletTester:
public class WalletTester {
public static void main(String args[]) {
// create a new Wallet object using an array
int a[] = {5, 50, 10, 5};
Wallet myWallet = new Wallet(a);
// show the contents of myWallet
System.out.println("myWallet contains: " + myWallet.toString());
// print the value of myWallet
System.out.println("\nvalue of myWallet is: $" + myWallet.value());
// transfer all the banknotes from myWallet to yourWallet!
Wallet yourWallet = new Wallet();
yourWallet.add(1);
yourWallet.transfer(myWallet);
System.out.println("\nnow myWallet contains: " + myWallet.toString());
System.out.println("yourWallet contains: " + yourWallet.toString());
}
}
When this program is ran, I get this output:
myWallet contains: Wallet[[I@d0a7f3]550105000000
now myWallet contains: Wallet[[I@d0a7f3]5555000000
yourWallet contains: Wallet[[I@99588e]15505500000
yourWallet with $5s removed is: Wallet[[I@99588e]1555500000
The output is suppose to be something similiar to this:
Wallet[5, 50, 10, 5]
Wallet[]
Wallet[1, 5, 10, 50, 5]