2014-10-01 57 views
0
package assignment; 
public class BankAccount { 
private double balance; 
private String accountHolderName; 

BankAccount() 
{ 
    balance = 0; 
    accountHolderName = ""; 
} 
BankAccount(double balance, String accountHolderName) 
{ 
    this.balance = balance; 
    this.accountHolderName = accountHolderName; 
} 
public String withdrawal(double withdrawalAmount) 
{ 
    String result = ""; 
    if(withdrawalAmount > balance) 
    { 
     result = "Account can not be overdrawn"; 
    }else if(withdrawalAmount <= 0) 
    { 
     result = "negative withdrawal amounts not allowed"; 
    } 
    else 
    { 
     balance -= withdrawalAmount; 
     result = "$ " +withdrawalAmount + " withdrawn. Remaining balance is: " +balance; 
    } 
    return result; 
} 

public String deposit(double amountToDeposit) 
{ 
    String result = ""; 
    if(amountToDeposit <= 0) 
    { 
     result = "Deposits must be positive"; 

    }else 
    { 
     balance += amountToDeposit; 
     result = "$ " +amountToDeposit + " deposited. Balance is: " + balance; 
    } 
    return result; 
} 


public String transfer(double amountToTransfer, BankAccount recipient) 
{ 
    String result = ""; 
    recipient.withdrawal(amountToTransfer); 
    recipient.deposit(amountToTransfer); 
    result = recipient.withdrawal(amountToTransfer) + "\n" +  recipient.deposit(amountToTransfer);; 
    return result; 
} 
public double getBalance() { 
    return balance; 
} 
public void setBalance(double balance) { 
    this.balance = balance; 
} 
public String getAccountHolderName() { 
    return accountHolderName; 
} 
public void setAccountHolderName(String accountHolderName) { 
    this.accountHolderName = accountHolderName; 
} 
@Override 
public String toString() { 
    return "BankAccount [balance=" + balance + ", accountHolderName=" 
      + accountHolderName + ", getBalance()=" + getBalance() 
      + ", getAccountHolderName()=" + getAccountHolderName() + "]"; 
} 


} 

BankAccount person1 = new BankAccount(500,“Steve”);找到执行对象

BankAccount person2 = new BankAccount(700,“Bob”);

在转移方法im卡住我应该如何将钱转移到person2.transfer(100,person1);

我不知道我会如何从person2对象中减去100。感谢您的帮助

+1

你的问题是什么?这个任务真的和在'撤销'方法中减去你自己无法解决你的问题的方法不同吗? – fabian 2014-10-01 22:16:10

+0

你的问题很不明确,似乎与你的头衔没有任何关系。对象不执行,线程可以执行。 – EJP 2014-10-02 00:07:38

回答

0

当您在银行账户对象上操作的对象(BankAccount)的方法(transfer())中时。所以你可以引用在同一个对象中定义的其他变量和方法。

public void transfer(double amount, BankAccount recipient) 
{ 
    if (balance >= amount) 
    { 
     balance -= amount; 
     //this balance variable represents the balance in the bank account 
     //object this money is coming from. 
     recipient.balance += amount; 
     //this balance variable is the balance of the recipient. 
     } 
} 

说的是,Java Trails确实不错。在这里试试这个。 Java Trails: Objects会向你解释对象是如何工作的。

+0

感谢帮助和链接真的很感激! – superhamster 2014-10-02 00:28:36