我正在学习Java入门课程,并且正在电子钱包实验室工作。

我需要将一个钱包(捐赠者钱包)的钱包内容转移到另一个(接收者钱包)的末尾。

我相信我的构造函数已正确设置。

    import.java.util.Arrays;

    public class Wallet
    {
       private static final int MAX = 10;  //Max possible # of banknotes in a wallet

   // instance variables
       private int contents[]; //array of banknotes
       private int count; //number of banknotes stored in contents[]

   /**
    * Default constructor for objects of class Wallet
    */
   public Wallet()
   {
        // initialize instance variables
        contents = new int[MAX];
        count = 0;
   }

   /**
    * Overloaded constructor for objects of class Wallet
    */
   public Wallet(int a[])
   {
       contents = new int[MAX];

       for (int i = 0; i<a.length; i++)
       {
            contents=a;
            if (contents[i] > 0)
                count++;
       }
   }


但需要帮助验证我编写的以下add()方法是否正确:

public void add(int banknote)//Not sure if this is right
   {
       StringBuilder sb = new StringBuilder();

       for (int i = 0; i<contents.length; i++)
                sb.append(contents[i] + ", ");

       sb.append(banknote);

       count++;

   }


或者应该是:

 contents[count] = banknote;
  count++;


我还需要将捐赠者钱包中的内容转移到接收者钱包中,清空捐赠者钱包并添加到接收者中,我编写了以下代码,但似乎不正确,无法正常工作:

 public void transfer(Wallet donor)
   {

      for(int i = 0; i < count; i++)
        {
            add(donor.contents[i]);
            count++;
        }
      donor.count=0;
   }


关于我可能在哪里弄错的任何指导,已经在这里呆了几个小时..谢谢

最佳答案

好吧,这应该可以解决一些问题:

public Wallet(int a[]) {
  contents = new int[MAX];
  count = 0;
  for (int i = 0; i < a.length; i++) {
    if (a[i] > 0)
      contents[count++] = a[i];
      // only increase your content position for actual notes
  }

public void add(int banknote) {
  contents[count++] = banknote;
  /* this version makes a lot more sense
   * as you actually mutate your instance */
}

public void transfer(Wallet donor) {
  for(int i = 0; i < donor.count; i++) // gotta use donor.count here
    add(donor.contents[i]);
  donor.count=0;
}

10-06 09:18