我的任务是创建一个小型银行程序,该程序保留两个账户,定期账户和储蓄账户。然而,当我即将完成一个粗略的版本时,我读到提示我应该使用我们在生病那天学到的东西,例外。
我不清楚如何使用异常或是否应该创建自己的异常类。我想要一个例外,以便在程序中的任何时候,如果输入以“q”或“Q”开头的内容,程序就会退出并结束。另一个规定是,如果储蓄低于 25 美元,则冻结账户。我想异常对于该功能来说是理想的。
public abstract class BankAccount {
int balance;
int deposits;
int withdrawals;
int annualInterestRate;
int charges;
public void _BankAccount(int newBalance, int newInterest) {
balance = newBalance;
annualInterestRate = newInterest;
}
public void Deposit(int newDeposit) {
balance = balance + newDeposit;
deposits++;
}
public void Withdraw(int newWithdraw) {
balance = balance - newWithdraw;
withdrawals++;
}
public void calcInterest() {
int monthlyInterestRate = (annualInterestRate / 12);
int monthlyInterest = balance * monthlyInterestRate;
balance = balance + monthlyInterest;
}
public void monthlyProcess() {
balance = balance - charges;
calcInterest();
deposits = 0;
withdrawals = 0;
}
}
public class SavingsAccount extends BankAccount {
boolean status;
public void savingWithdraw(int newWithdraw) {
if (balance < 25) {
System.out.println("Error – Not enough funds.");
} else {
Withdraw(newWithdraw);
}
}
public void savingDeposit(int newDeposit) {
if (balance < 25) {
Deposit(newDeposit);
System.out.println("Savings account is now active.");
} else {
Deposit(newDeposit);
}
}
public void savingMonthlyProcess() {
if (withdrawals > 4) {
charges = ((withdrawals - 4) * 1);
balance = balance - ((withdrawals - 4) * 1);
if (balance < 25) {
System.out.println("Savings account is now inactive.");
}
}
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String choice;
int num = 0;
boolean quit = false;
do {
System.out.println("Which account would you like to access, regular or savings?:");
choice = in.nextLine();
if (choice.equals("regular")) {
num = 0;
}
if (choice.equals("savings")) {
num = 1;
}
switch (num) {
case 0:
System.out.println("What action do you wish to perform \n(Withdraw, deposit, monthly processing)?:");
choice = in.nextLine();
if (choice.equals("withdraw")) {
num = 0;
}
if (choice.equals("deposit")) {
num = 1;
}
if (choice.equals("monthly processing")) {
num = 2;
}
switch (num) {
case 0:
System.out.println("Enter amount to withdraw:");
Withdraw(in.nextInt());
case 1:
System.out.println("Enter amount to withdraw:");
Deposit(in.nextInt());
case 2:
MonthlyProcess();
}
case 1:
System.out.println("What action do you wish to perform \n(Withdraw, deposit, monthly processing)?:");
choice = in.nextLine();
if (choice.equals("withdraw")) {
num = 0;
}
if (choice.equals("deposit")) {
num = 1;
}
if (choice.equals("monthly processing")) {
num = 2;
}
switch (num) {
case 0:
System.out.println("Enter amount to withdraw:");
savingsWithdraw(in.nextInt());
case 1:
System.out.println("Enter amount to withdraw:");
savingsDeposit(in.nextInt());
case 2:
savingMonthlyProcess();
}
}
}
}
}