如何获取这些设置并获取更新方法而不是覆盖值?

时间:2014-08-06 19:39:45

标签: java class methods

如何获取这些设置并获取更新方法而不是覆盖值?例如,如果我设置$ 1500的信用额度,然后使用spendMoney(500)然后使用spendMoney(250),我希望getCreditBalance返回$ 750的运行总计,但是getCreditBalance只返回输入的最后一个数量,250 in这种情况。

public class CreditCard
{  
 //Source: RR 08/06/14
 private int creditLimit;
 private double spend;
 private double payBalance;
 private double creditBalance;

public CreditCard()
{
  creditLimit = 0;
  creditBalance = 0.0;
  spend = 0.0;
  payBalance = 0.0;
}

public void setCreditLimit(int m)
{
  creditLimit = m;
}

public int getCreditLimit()
{
  return creditLimit;
}

public double spendMoney(double s)
{
  if(spend > creditLimit || spend > creditLimit - creditBalance)
  {
     System.out.println("Credit Limit Exceeded");
  }
  else
  {
     spend = s;
  }
  return spend; 
}

public double payCreditBalance(double pay)
{
  payBalance = pay;
  return payBalance;
}

public double getCreditBalance()
{
  creditBalance = spend - payBalance;
  return creditBalance;
}   
}

2 个答案:

答案 0 :(得分:2)

您应该将花费的金额(s)添加到总花费(spend

public double spendMoney(double s)
{
  if(spend > creditLimit || spend > creditLimit - creditBalance)
  {
     System.out.println("Credit Limit Exceeded");
  }
  else
  {
     spend += s;
  }
  return spend; 
}

并从spend中扣除已用完的资金(payBalance)以获取creditBalance

public double getCreditBalance()
{
  creditBalance = payBalance - spend;
  return creditBalance;
}  

答案 1 :(得分:0)

我认为你想增加你花的金额,而不是分配它。

spend += s;