给出错误的结果。我该怎么办?

时间:2013-05-20 08:12:48

标签: java

我正在尝试计算一个简单的银行函数。我通过一个方法从执行类到另一个传递了两个撤销值150和47.62。但它需要两次47.62并且给出错误的结果这里是执行类。

public class Account {
  public double balance ;
  public double deposite;
  public double withdraw;
  public Account(double balance) {
    this.balance = balance;
  }
  public double getBalance() {
    return balance;
  }
  public void setBalance(double balance) {
    this.balance = balance;
  }
  public double getDeposite() {
    balance = balance + deposite;
    return deposite;
  }
  public void setDeposite(double deposite) {
    this.deposite = deposite;

  }
  public double getWithdraw() {
    return withdraw;
  }
  public void setWithdraw(double withdraw) {
    this.withdraw = withdraw;
    if(withdraw <= balance){
      balance =  balance - withdraw;
    }
  }
  public boolean withdraw(double wamt)
  {
    boolean result = false;
    if(withdraw <= wamt)
    {
      balance= balance - withdraw;
      return true;
    }
    return result; 
  }
}

我的客户类

public class Customer {
  private String firstName;
  private String lastName;
  Account account;
  public Customer(String firstName, String lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
    //this.account = account;
  }
  public String getFirstName() {
    return firstName;
  }
  public void setFirstName(String firstName) {
    this.firstName = firstName;
  }
  public String getLastName() {
    return lastName;
  }
  public void setLastName(String lastName) {
    this.lastName = lastName;
  }
  public Account getAccount() {
    return account;
  }
  public void setAccount(Account account) {
    this.account = account; }   
}

主要课程:

public class BankProjectDemo {
  public static void main(String[] args) {
    double balance = 500;
    Customer cust = new Customer("asasd0","asdasda");
    Account accnt = new Account(balance);
    System.out.println("Creating customer:  " +cust.getFirstName());
    accnt.setWithdraw(150);
    accnt.setDeposite(22.50);
    System.out.println("Withdraw1  "+accnt.getWithdraw());
    System.out.println("Depsoite  "+accnt.getDeposite());
    Account accnt1 = new Account(balance);
    accnt1.setWithdraw(47.62);
    System.out.println("Withdraw2 "+accnt1.getWithdraw()+"  " + accnt1.withdraw(balance));
    System.out.println("Balance " + accnt.getBalance());
  }
}

3 个答案:

答案 0 :(得分:1)

public double getDeposite() {
    balance = balance + deposite;
    return deposite;
  }

这个方法看起来不对,每次你返回一个你正在递增另一个变量的变量时 - 这意味着你调用这个方法的次数越多,余额就越大。这是故意吗?

另外 - 你应该研究一些基本的单元测试以及调试,这样就可以更清楚地看到不同变量的确切情况。

答案 1 :(得分:1)

 public boolean withdraw(double wamt)
  {
    boolean result = false;
    if(withdraw <= wamt)
    {
      balance= balance - withdraw;
      return true;
    }
    return result; 
  }

你减少余额withdraw()setWithdraw()所以你设置一次,然后再次减少你的系统println,这就是为什么最后你得到两倍的减少

答案 2 :(得分:0)

也许问题就在这里

System.out.println("Balance " + accnt.getBalance());

应该是

System.out.println("Balance " + accnt1.getBalance());