-1
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)
{


}}

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

4

3 回答 3

1

使用它来引发异常。

throw new InsufficientBalanceException();

并将方法声明为

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

希望这可以帮助。

于 2013-04-16T15:49:26.553 回答
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;
}
于 2013-04-16T15:49:31.577 回答
0
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% 工作...

于 2019-04-29T09:56:20.010 回答