Java ATM机器 - 如何从用户输入(输入帐号)中添加对象(银行帐户)



在我的Java类中,我们必须创建两个应该是银行帐户的对象。

示例:

Account account1 = new Account();
account1.setName("Isabella");
account1.setBalance(50.00);

Account account2 = new Account();
account2.setName("Oscar");
account2.setBalance(1000.00);

我的教授希望我们能够在用户选择选项(例如"帐户信息"(时显示信息。但是在此之前,用户必须放入一个帐号,特别是101或102。问题是我不了解如何以选择该方法的方式分配此数字。

//accesor methods
public String getName() {
    return this.name;
}
public int getId() {
    return this.id;
}
public double getBalance() {
    return this.balance;
}
public double getInterest() {
    return this.interest;
}
//mutator methods
public void setName(String name) {
    String accName = null;
    this.name = accName;
}
public void setBalance(double balance) {
    double accBalance = 0;
    this.balance = accBalance;
}
public void setInterest(double interest) {
    double monthlyInterest = 0;
    this.interest = monthlyInterest;
}

这些是我的饰物和突变器,我不知道它是否相关吗?我的教授说,我们需要为ID制作一个(帐号(,但只为该ID制作一个登录器....

您的教授告诉您是否可以更改类构造函数?
您可以更改Account类的类构造函数如下:

Account(int acId)
{
    this.id = acId;
}

然后在您的代码中调用构造函数,例如:

Account account1 = new Account(101);
...
Account account2 = new Account(102);

听起来像是帐户 id 应该是必需不变的

您需要将其添加到Account构造函数,例如

public class Account {
    public final int id; // final means this cannot be changed once assigned
    // other fields
    public Account(final int id) {
        this.id = id;
    }
    // getters, setters, etc
}

现在您可以通过

获得(访问(帐户ID
account1.id

有些人不是public final属性的粉丝

public class Account {
    private final int id; 
    // other fields
    public Account(final int id) {
        this.id = id;
    }
    public int getId() {
        return id;
    }
    // getters, setters, etc
}

至于通过ID检索帐户,听起来您需要一个带有id->帐户地图的银行。例如

public class Bank {
    private Map<Integer, Account> accounts = new HashMap<>();
    public void addAccount(final Account account) {
        accounts.put(account.id, account); // or account.getid()
    }
    // using Optional as I cannot stand @Nullable return types
    public Optional<Account> getAccount(final int id) {
        return Optional.ofNullable(accounts.get(id));
    }
}

最新更新