2016-02-07 3 views
0

Мне нужно выбросить исключение из «недостаточных средств», когда пользователь снимает больше, чем сумма в initialAccountBalance (что равно 500,00). Однако я не уверен, где поставить исключение.Необходимо показать «Недостаточно средств» для отрицательных сумм

public static void main(String[] args) { 

    Scanner in = new Scanner(System.in); 

    double initialAccountBalance = 500.00; 

    System.out.print("Enter a transaction type (Balance, Deposit, or Withdrawal): "); 
    String transactionType = in.nextLine(); 

    if (transactionType.equalsIgnoreCase("Balance")){ 
     System.out.println("Balance " +initialAccountBalance); 
     System.out.println(); 

    } else if (transactionType.equalsIgnoreCase("Deposit")){ 
     System.out.println("Enter deposit: "); 
     int deposit = in.nextInt(); 
     double balance = initialAccountBalance + deposit; 
     System.out.printf("Account Balance: %8.2f", balance); 

    } else if(transactionType.equalsIgnoreCase("Withdrawal")){ 
     System.out.println("Enter withdrawal: "); 
     int withdrawal = in.nextInt(); 
     double balance = initialAccountBalance - withdrawal; 
     System.out.printf("Account Balance: %8.2f", balance); 

    } else { 
     System.out.println("Invalid transaction type"); 
    } 
} 
+0

вам нужно создать класс, который расширяет InsufficientBalanceException исключения, то в вашем коде вы делаете: if (что-то ....) бросаете новый InsufficientBalanceException(); – chenchuk

ответ

0

Вы можете разместить if сразу после того, пользователь вводит сумму вывода, как это:

//... 
System.out.println("Enter withdrawal: "); 
int withdrawal = in.nextInt(); 
if (withdrawal > initialAccountBalance) 
    throw new RuntimeException("Insufficient Funds"); 
double balance = initialAccountBalance - withdrawal; 
System.out.printf("Account Balance: %8.2f", balance); 
//... 

If вы хотите бросить свое собственное исключение, вам нужно создать новый класс, который расширяет Exception, как @chenchuk, упомянутый в комментариях.

public class InsufficientFundsException extends Exception{ 
    //if you need to you can Overwrite any method of Exception here 
} 

Таким образом, вы можете бросить InsufficientFundsException в основном методе:

//... 
System.out.println("Enter withdrawal: "); 
int withdrawal = in.nextInt(); 
if (withdrawal > initialAccountBalance) 
    throw new InsufficientFundsException(); 
double balance = initialAccountBalance - withdrawal; 
System.out.printf("Account Balance: %8.2f", balance); 
//... 

но вы должны предоставить какой-то способ обработки исключений либо с помощью примерки поймать блок или добавление броски декларации к голосу метода. Но вы должны посмотреть, что вверх, это должно многому объяснить в глубине здесь ...

Надеется, что это поможет вам немного (:.

0
... 
} else if (transactionType.equalsIgnoreCase("Withdrawal")){ 
    System.out.println("Enter withdrawal: "); 
    int withdrawal = in.nextInt(); 

    if (withdrawal > initialAccountBalance) { 
     throw new InsufficientFundsException("Insufficient Funds"); 
    } 

    double balance = initialAccountBalance - withdrawal; 
    System.out.printf("Account Balance: %8.2f", balance); 

} 
... 

И ваш InsufficientFundsException должно быть так:

public class InsufficientFundsException extends Exception { 

    private static final long serialVersionUID = -1L; 

    public InsufficientFundsException() { 
    } 

    public InsufficientFundsException(String message) { 
     super(message); 
    } 
} 
Смежные вопросы