我有一项任务是创建一个小银行计划,保留两个帐户,定期和节省。然而,当我即将完成一个粗略的版本时,我读到了提示,我想要使用我们在生病那天学到的东西,例外。
我不清楚如何使用异常或者我应该创建自己的异常类。我想要一个例外,这样在程序中的任何一点如果输入以'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();
}
}
}
}
}
答案 0 :(得分:0)
异常用于处理不需要的情况。在您的情况下,您可以使用内置的异常类来处理大多数运行时异常,但使用自定义消息。
另一项规定是如果节省的费用低于25美元以冻结账户。
对于上述情况,您可以很好地创建一个新的异常类,并使用用户定义的错误消息处理此异常。
您可以在Exception handling in java上阅读更多信息。