使用对象/方法进行Java编程

时间:2014-11-24 19:44:19

标签: java

我无法在存款后取得余额并退出停留,而是返回到初始余额并执行操作。

我要求它退出2500,这应该留给我17500,但后来我有3000存款,这应该给我20500,但我得到23000。

另外,我的日期输出仍然是“null”。

这是第一个Class文件。

import java.util.Date;

public class Account
{
   private int id;
   private double balance;
   private double annualInterestRate;
   private Date dateCreated;
   private double withdraw;
   private double deposit;

   Account()
   {
      id = 1;
      balance = 1;
      annualInterestRate = 1;
   }

   Account(int newID, double newBalance, double newAnnualInterestRate)
   {
      id = newID;
      balance = newBalance;
      annualInterestRate = newAnnualInterestRate;   
   }

   public int getId()
   {
      return id;
   }

   public double getBalance()
   {
      return balance;
   }

   public double getAnnualInterestRate()
   {
      return annualInterestRate;
   }

   public double getMonthlyInterestRate()
   {
      return (annualInterestRate / 12) / 100;
   }

   public double getMonthlyInterest()
   {
      return balance * getMonthlyInterestRate();
   }

   public double getWithdraw(double amount)
   {
      amount = balance - amount;
      return amount;
   }

   public double getDeposit(double amount)
   {
      amount = balance + amount;
      return amount;
   }

   public Date getDateCreated()
   {
      return dateCreated;
   }
}

这是测试类文件

public class TestAccount
{
   public static void main(String[] args)
   {
      Account A = new Account(1122, 20000, 4.5);

      System.out.println("Account number: " + A.getId());
      System.out.println("The Account balance is: $" + A.getBalance() + "0");
      System.out.println("The Annual Interest Rate is: " + A.getAnnualInterestRate()+ "%");
      System.out.println("The Account balance after a $2,500 withrawal is: " + A.getWithdraw(2500));
      System.out.println("The Account balance after a $3,000 deposit is: " + A.getDeposit(3000));
      System.out.println("The monthly interest earned is: " + A.getMonthlyInterest());
      System.out.println("The account was created on: " + A.getDateCreated());   
   }
}

2 个答案:

答案 0 :(得分:3)

您正在修改本地变量amount,而不是修改balance。在getWithdraw中,更改

amount = balance - amount;

balance = balance - amount;

同样适用于getDeposit方法。

顺便说一下,不清楚为什么要调用这些方法getWithdrawgetDeposit,因为这些方法分别提取和存款。我会打电话给他们withdrawdeposit。我也没有找到在两种方法中返回参数值amount的目的。这两种方法都不需要返回任何内容,可以指定返回void

此外,我没有为dateCreated分配任何内容,因此它null。您可以为此实例变量添加setter方法。

答案 1 :(得分:1)

getWithdrawgetDeposit方法中,您可能应该更改balance,而不是amount。也没有理由从这些方法中返回amount

您永远不会在我能看到的任何地方创建Date对象,因此您的日期为null。根据{{​​1}}方法的名称,我猜测应该将日期设置为创建帐户的日期,因此您应该在getDateCreated构造函数中执行此操作。