足够的平衡异常

时间:2013-04-16 15:40:37

标签: java exception

import java.util.Scanner;
public class Bankaccount{
    double diposit, withdraw;
 double balance=0;
 public Bankaccount(double balance)
 {
     this.balance=balance;
 }
  void deposit(double ammount)
{
       Scanner b=new Scanner(System.in);
    System.out.println("diposit a amount");
     ammount=b.nextInt();
     balance +=ammount;
}
 void withdraw(double ammount)
{
       Scanner b=new Scanner(System.in);
    System.out.println("withdraw a amount");
     ammount=b.nextInt();
     balance +=ammount;
}

  void display()
  {
      System.out.println(balance);
  }
public static void main(String[]args)
{


}}

如何在主要功能中显示这些条件?由于余额不足,我已经为此创建了一个例外。我想在这里抛出异常。

3 个答案:

答案 0 :(得分:1)

使用此方法抛出异常。

throw new InsufficientBalanceException();

并将方法声明为

void withdraw (double amount) throws InsufficientBalanceException
{
    if (amount > balance)
        throw new InsufficientBalanceException();
    else
        balance -= amount;
}

希望这有帮助。

答案 1 :(得分:1)

import java.util.*;
import java.util.Scanner;
class DebitException 
{ 
    static void fun() throws IllegalAccessException 
    { 
        double balance = 0, damount, wamount;

        Scanner dep=new Scanner(System.in);
        System.out.println("Deposit an amount");
        damount=dep.nextInt();
        balance += damount;

        Scanner wd=new Scanner(System.in);
        System.out.println("Withdraw an amount");
        wamount=wd.nextInt();
        balance -= wamount;


        if (balance<0)
        {
        throw new IllegalAccessException(); 
        }
        else
        System.out.println(balance);
    }



    public static void main(String args[]) 
    { 

        try
        { 
            fun(); 
        } 
        catch(IllegalAccessException ex) 
        { 
            System.out.println("Exceeding Balance"); 
        } 
    } 
} 

您可以使用此代码...此代码将100%有效...

答案 2 :(得分:0)

首先,当你退出时,你必须减去不添加的数量,但首先你必须检查你是否可以减去这个数额:

void withdraw(double ammount) throws InsuffcientBalanceExeption
{
    Scanner b=new Scanner(System.in);
    System.out.println("withdraw a amount");
    ammount=b.nextInt();
    if(balance<amount){
       throw new InsuffcientBalanceExeption();
    }
    balance -=ammount;
}