4 回答

TA贡献1805条经验 获得超9个赞
我想我明白你在说什么,我已经检查了你的代码,但我认为那里有一些冗余代码,比如你的“帐户来自”。如果您是一个帐户的所有者并且您要转移到另一个帐户,您需要指定您的帐号吗?你明白?
其次,最好使用多个 if 和 else-if 来切换 case 语句。
class bankAccount {
String name;
private double balance;
private final long acctNum = ThreadLocalRandom.current().nextLong(100000000, 999999999);
public bankAccount(String name, double balance) {
this.name = name;
this.balance = balance;
System.out.println("HELLO " + name + ", Your account number is: " + acctNum);
}
public void setName(String name) {
this.name = name;
}
public void addFunds(int amount) {
this.balance += amount;
}
public void withdrawFunds(int amount) {
this.balance -= amount;
}
public double getBalance() {
return balance;
}
public long getAcctNum() {
return acctNum;
}
public void transfer(bankAccount name, double amount) {
if(this.balance >= amount) {
name.balance += amount;
this.balance -= amount;
System.out.println("Transaction Successful");
}
else {
System.err.println("Insufficient Funds!");
}
}
}
class BankSimulator {
static bankAccount John = new bankAccount("John", 50000);
static bankAccount James = new bankAccount("James", 3000);
public static void main(String[] args) {
John.transfer(James, 300);
System.out.println("John's new balance is "+ John.getBalance());
System.out.println("James' new balance is "+ James.getBalance());
}
}
由于您将使用另一个account,因此您应该创建该类的两个实例Account,这将澄清要转移到哪些帐户之间的歧义。
基本上我所做的就是创建 Account 类,创建一个名为John(John's Account) 的实例并创建一个名为 (James' Account) 的实例James,所以现在,你有两个帐户类,它们具有不同的字段但相似的方法(getBalance(), transfer(), getAcctNum(), addFunds(), withdrawFunds())。
我希望这就是您所需要的,祝您编码愉快!

TA贡献1850条经验 获得超11个赞
您需要跟踪列表或地图中的所有帐户。然后您使用用户输入搜索并检索所需的帐户。此外,我认为您不需要 Account 对象中的 transfer 方法,您可以只使用 main 中的 withdraw 和 addFunds,或者像静态方法一样使用它。此外,我认为您将需要一些额外的操作,例如创建新帐户以及可能只会更改活动帐户的登录名。目前您只有 1 个账户,即 a1,因此转移任何东西都没有意义。

TA贡献1795条经验 获得超7个赞
我建议您先创建虚拟数据(现有)帐户:
List<Account> accountList = new ArrayList<>();
Account acct1 = new Account("tester1", 100.0);
Account acct2 = new Account("tester2", 100.0);
accountList.add(acct1);
accountList.add(acct2);
为 Account 添加构造函数以便于添加 Accounts:
public Account(String name, double balance) {
this.name = name;
this.balance = balance;
}
将新帐户帐户存储在列表中:
accountList.add(a1);
对于用于传输的“(toDo == 6)”的程序:
首先检查 accountList 是否至少有 2 个帐户,因为如果只有 1 个帐户就没有意义。
else if (toDo == 6) {
if (accountList.size() > 2) {
System.out.println("Enter the account you would like to transfer money from:");
String fromAccount = scan.next();
System.out.println("Enter the account you would like to transfer money to:");
String toAccount = scan.next();
System.out.println("Enter the amount of money you would like to transfer: $");
double moneyToTransfer = scan.nextDouble();
for (Account account : accountList) {
if (account.getName().equals(fromAccount)) {
account.withdraw(moneyToTransfer);
}
if (account.getName().equals(toAccount)) {
account.addFunds(moneyToTransfer);
}
}
} else
System.out.println("Cannot transfer.");
}
还要考虑该帐户是否实际存在,因此添加额外的检查。希望这可以帮助!
添加回答
举报