我很难找到一种方法,只需使用String builder就可以将int数组转换为String。在我的toString方法中,我是否正在使用右循环?
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();
}
}
这是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());
}
}
运行此程序时,我得到了这个输出:
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
输出结果与此类似:
Wallet[5, 50, 10, 5]
Wallet[]
Wallet[1, 5, 10, 50, 5]