首页 > 解决方案 > 向另一个类请求双精度时出错

问题描述

我需要制作一个菜单,以便用户可以选择他想要对我正在构建的银行应用程序执行的操作。用户有以下选项:

>1. Select a bank account. 
>2. Check the account balance.
>3. Depositing money into the account 
>4. Withdraw money from the account
>5. Transfer money from one account to another account 

要启用此功能,我们将向 BankAccountService 添加以下方法,您可以在下面的 UML 方案中看到。

>1. getAccount (String accountNumber)
>2. getAccountBalance (Account account)
>3. deposit (Account account, double amount)
>4. withdraw (Account account, double amount) 
>5. transfer (Account source, Account target, double amount)

UML

package BankProject;

import java.util.*;

public class BankAccountService {
    private BankAccount[] accounts;

public void addBankAccount(final BankAccount account)
{
    if (accounts == null)
    {
        accounts = new BankAccount[10];
    }

    int index = 0;

    while (accounts[index] != null)
    {
        index++;

        if (index >= accounts.length)
        {
            accounts = Arrays.copyOf(accounts, accounts.length + 10);
        }
    }

    accounts[index] = account;


}


public void getAccountBalance(final BankAccount account) {
    double getAccountBalance = new BankAccount(getAccountBalance());
}
}

如您所见,当我尝试添加该方法时出现错误。 错误

请记住,我以前从未编码过,我不知道为什么会出现这个错误。谁能告诉我添加此方法的正确方法?

通过添加以下代码,我确实找到了一种获取主文件夹中所有帐户余额的方法:

double balance = bankAccountService.getAccountBalance();
System.out.println(balance);
double balance2 = account1.balance;
System.out.println(balance2);
double balance3 = account2.balance;
System.out.println(balance3);

但在 UML 中,它要求我在 BankAccountService 中添加代码。我不知道为什么需要这样做,如果可以从 main 中做到这一点。

标签: javaclassdouble

解决方案


如果 BankAccount 中的 balance 属性是私有的,你应该为它创建一个 getter,然后:

public void getAccountBalance(BankAccount account) {
    double accountBalance = account.getBalance();
}

所以在 BankAccount.java 你应该添加:

public double getBalance() {
   return this.balance;
}

推荐阅读