Run Savings Account

You might also like

Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 2

package monterde;

import java.util.Scanner;
class SavingsAccount {
private double balance;
public static double interestRate = 0;

public SavingsAccount() {
balance = 0;
}

public double getBalance() {


return balance;
}

public static double getInterestRate() {


return interestRate;
}

public static void setInterestRate(double newRate) {


SavingsAccount.interestRate = newRate;
}

public void deposit(double amount) {


balance += amount;
}

public double withdraw(double amount) {


if (balance >= amount) {
balance -= amount;
}
else {
amount = 0;
}
return amount;
}

public void addInterest() {


double interest = balance * interestRate;
balance += interest;
}

public static void showBalance(SavingsAccount account) {


System.out.printf("Balance is $%.2f\n", account.getBalance());
}
}

public class RunSavingsAccount {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
SavingsAccount savings = new SavingsAccount();

System.out.print("Enter interest rate: ");


SavingsAccount.setInterestRate(sc.nextDouble());

System.out.print("Enter initial deposit amount: ");


savings.deposit(sc.nextDouble());

char choice;
while (true) {
System.out.print("\nEnter D for another deposit or W for withdraw: ");
choice = Character.toUpperCase(sc.next().trim().charAt(0));

if (choice == 'D') {
System.out.print("Enter amount to be deposited: ");
savings.deposit(sc.nextDouble());
}
else if (choice == 'W') {
System.out.print("Enter amount to be withdrawn: ");
double withdrawn = savings.withdraw(sc.nextDouble());
if (withdrawn == 0) {
System.out.println("-> You don't have sufficient balance!");
}
else {
System.out.println("-> Amount successfully withdrawn!");
}
}
else {
System.out.println("-> Invalid option selected! Try again...");
continue;
}

if (savings.getBalance() > 1000) {


savings.addInterest();
}
SavingsAccount.showBalance(savings);
break;
}
}
}

You might also like