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.");
}
還要考慮該帳戶是否實際存在,因此添加額外的檢查。希望這可以幫助!
添加回答
舉報