[英]Accessing account balance in Bank System application
我目前正在尝试创建一个简单的银行程序,用户可以在其中创建帐户、存款和取款。 问题是我在创建帐户时遇到了问题。
这是我的主要内容:
Account account = new Account();
account.createAccount(1000, "Bob");
这是我的 Account.java 类:
public void createAccount(int bal, String name){
int balance = bal;
String username = name;
System.out.println("An account has been set up for "+name+", with a balance of $"+bal+".");
我遇到的问题是访问创建的帐户。 帐户已创建并运行,但我不确定如何访问该帐户。
我想添加一个方法,您可以在其中调用帐户的余额,但不确定如何执行此操作。 任何帮助将不胜感激。
您没有显示太多Account
类(这很好——有一个最小的可重现示例很好,但最好使用完全可编译的代码片段),所以我的回答将带有一些假设:
我假设您当前的课程如下所示(为简洁起见,消除空格):
public class Account {
public void createAccount(int bal, String name) {
int balance = bal;
String username = name;
System.out.println("An account has been set up for "+name+", with a balance of $"+bal+".");
}
}
正如@ScaryWombat 在他的评论中指出的那样,您需要将balance
和username
变量从createAccount
方法中移出并作为字段移入类中。 然后在createAccount
方法中设置这些字段:
public class Account {
private int balance = bal;
private String username = name;
public void createAccount(int bal, String name) {
this.balance = bal;
this.username = name;
System.out.println("An account has been set up for "+name+", with a balance of $"+bal+".");
}
}
现在,一个Account
实例拥有一个余额和一个名称,当您调用createAccount
时,这些名称会被覆盖。
但是,我们仍然有问题。 每次调用createAccount
,数据都会被覆盖。 例如在这段代码中,Bob 的账户将被遗忘,Alice 的账户将覆盖数据:
Account account = new Account();
account.createAccount(1000, "Bob");
account.createAccount(2000, "Alice");
这就是构造函数的createAccount
。我们将把逻辑移到Account
构造函数中,而不是createAccount
方法:
public class Account {
private int balance = bal;
private String username = name;
public Account(int bal, String name) {
this.balance = bal;
this.username = name;
System.out.println("An account has been set up for "+name+", with a balance of $"+bal+".");
}
}
有了这个,创建帐户的唯一方法是在对new Account()
的调用中指定起始详细信息:
Account bobsAccount = new Account(1000, "Bob");
Account alicesAccount = new Account(2000, "Alice");
但是,我们仍然没有解决您问题的核心:如何访问余额? 以下将导致错误:
bobsAccount.balance = 2000;
这是因为balance
字段是私有的(应该是这样)。 我们需要的是在Account
类中添加访问器方法:
public class Account{
...
public void setBalance(int newBalance) {
balance = newBalance;
System.out.println(name+"'s account balance is now $"+bal+".");
}
public int getBalance() {
return balance;
}
...
}
您可能会问“为什么要遇到这个麻烦?”,好吧,我们可以添加检查(例如,不允许余额低于零),添加日志记录以审核对余额的访问,甚至没有setBalance
或getBalance
,而只有transferFrom(Account otherAccount)
和transferTo(Account otherAccount)
(确保永远不会添加资金,而只会在系统中转移)。
附注。 正如其他评论中指出的那样, int
对货币金额从来没有好处。 您需要的是使用其他内容(例如BigDecimal
)来存储实际值的Currency
类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.