瀏覽代碼

(feat) Implement exercise section 4 - SavingsAccount

main
Rob Hallam 1 年之前
父節點
當前提交
a05a149c05
共有 1 個檔案被更改,包括 70 行新增0 行删除
  1. +70
    -0
      week23.java

+ 70
- 0
week23.java 查看文件

@@ -88,6 +88,10 @@ class BankAccount {
return balance;
}

public void setBalance(double balance) {
this.balance = balance;
}

public void deposit (double amount) {
this.balance += amount;
}
@@ -216,3 +220,69 @@ class DemoStudentLecturer {
System.out.println(String.format("%s\t\t&\t\t%s", adrian, trefusis));
}
}

class SavingsAccount extends BankAccount {
@Override
public String toString() {
return "SavingsAccount [interestRate=" + interestRate + "]";
}

private double interestRate;

/** Set up savings account for the thrifty
* @param person A {@link Person} object
* @param interestRate Expressed as %
*/
public SavingsAccount(Person person, double interestRate) {
super(person);
this.interestRate = interestRate;
}

@Override
public void withdraw(double amount) {
if (amount <= this.getBalance()) {
this.setBalance(this.getBalance() - amount);
}
}

public void addInterest() {
this.setBalance(this.getBalance() + (this.getBalance() * (this.interestRate / 100)));
}
}

class DemoSavingsAccount {
public static void main(String[] args) {
Person hotblack = new Person();
hotblack.setName("Hotblack Desiato");

SavingsAccount savings1 = new SavingsAccount(hotblack, 6);
savings1.deposit(100.00);

System.out.println(String.format("%s plays a gig with DA and gets paid", hotblack));
System.out.println(String.format("Account:\n\t%s", savings1));
System.out.println(".".repeat(80));

System.out.println(
String.format("%s has a PGGB and tries to take out £200 to cover the cleanup expenses!", hotblack));
savings1.withdraw(200.00);
System.out.println(String.format("Account:\n\t%s", savings1));
System.out.println(String.format("Fortunately (?), his bank blocks the transaction."));
System.out.println(".".repeat(80));

System.out.println(String.format("After 1 year, %s's account accrues interest!", hotblack));
savings1.addInterest();
System.out.println(String.format("Account:\n\t%s", savings1));
System.out.println(String.format("%s wonders what it would be like after 1000 years...", hotblack));
System.out.println(".".repeat(80));

for (int i=0; i < 999; i++) {
savings1.addInterest();
if (i % 20 == 0) {
System.out.printf("%.2f\t", savings1.getBalance());
}
}
System.out.println(String.format("...finally, after 1000 years spent dead for tax purposes, %s checks his account", hotblack));
System.out.println(String.format("Account:\n\t%s", savings1));

}
}

Loading…
取消
儲存