向数组添加值

时间:2016-11-01 06:31:28

标签: java arrays methods constructor

我有一个方法需要将提供的银行帐户添加到我创建的数组中:

public boolean addAccount (BankAccount newAccount[]) {
        if (numAccounts == 0) {
            return false;
        }
        else {
            return true;
            for(int counter=0; counter<newAccount.length; counter++)
                newAccount[counter] += accounts;
        }
    }

通过这种方法测试:

public static boolean test5() {
    System.out.println("Test5: add an account to a customer.");
    BankAccount b = new BankAccount();
    Customer c1 = new Customer("Alice", "Smith");
    customerCounter ++;
    if (!c1.addAccount(b))
        return false;

    return c1.toString().equals("Alice Smith, " + c1.getCustomerID() + "\n" + b.toString() + "\n");
}

但是我收到一个错误,eclipse在这行中没有解决方案:

newAccount[counter] += accounts;

2 个答案:

答案 0 :(得分:0)

首先,您需要提高代码质量。重新设计您的功能和数据结构。

  • 在addAccount函数中,您从哪里派生/操纵'numAccounts'?
  • 在方法参数中,使用List而不是数组'BankAccount newAccount []'。使用like(列出帐户)。然后你可以使用accounts.add()方法。
  • 'accounts'的定义是什么?
  • 你真的需要从这个方法中返回任何东西吗?
  • 返回语句后
  • ,不会执行任何代码。将'return'语句作为最后一个语句。

粘贴完整代码以了解整体结构。

答案 1 :(得分:0)

如果您只想查看如何将新值添加到数组中,那么它就是......

    int myArray[]={10,20,30};
    int newNumber=200;   //new value to be added

    /*Size of an array doesn't change once it is initialized,so a new Array must be 
      created (with new Size )to add new values.*/
    int newArray[]=new int[myArray.length+1];

    //The newArray will have {0,0,0,0};

    // Now copy all the data from previous array to new array.
    for(int i=0;i<myArray.length;i++)
        newArray[i]=myArray[i];

   //Now the content of newArray is {10,20,30,0}

    newArray[newArray.length-1]=newNumber;

    //Now the final content of newArray is {10,20,30,200}.

现在,尽管如此,我同意@Turing85和@ Shafiul。根据您的上述代码,您最终会得到无法访问的代码以及类型不兼容错误,是的,请重新设计您的代码。