【问题标题】:Adding a Value to an Array向数组添加值
【发布时间】:2017-03-14 07:14:18
【问题描述】:

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

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;

【问题讨论】:

标签: java arrays methods constructor


【解决方案1】:

首先你需要提高代码质量。重新设计你的函数和数据结构。

  • 在 addAccount 函数中,您在哪里派生/操作“numAccounts”?
  • 在方法参数中,使用 List 而不是数组“BankAccount newAccount[]”。使用喜欢(列出帐户)。然后你可以使用 accounts.add() 方法。
  • “帐户”的定义是什么?
  • 您真的需要从此方法返回任何内容吗?
  • return 语句后,不会执行任何代码。将“return”语句移至最后一条语句。

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

【讨论】:

    【解决方案2】:

    如果你只是想看看如何将新值添加到数组中,那么这里就是......

        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。使用上面的代码,你最终会得到 unreachable codeType Incompatible 错误,是的,请重新设计您的代码。

    【讨论】:

    • 如果我想将我的数组初始化为 null 条目,我可以只为 int myArray[]=null 输入 null 吗?
    • 如果你这样做,那么你的数组将不会指向任何东西。但如果你想要空条目,那么你必须将数组的数据类型更改为字符串。
    猜你喜欢
    • 2010-09-17
    • 1970-01-01
    • 2023-04-10
    • 1970-01-01
    • 2021-03-24
    • 2012-07-04
    • 1970-01-01
    • 1970-01-01
    • 2021-05-03
    相关资源
    最近更新 更多