首页 > 解决方案 > 带有异常处理的java ATM程序模拟 - 没有错误也没有完整输出

问题描述

输出不是完整的,也没有处理异常。请帮忙。

public class ATM {

    private String message;

    public ATM(String m) {
        if (m == null || m.trim().equals(""))
        throw new IllegalArgumentException("ATM name cannot be empty");
        else {
            message = m;
            System.out.println("Name is   " + message);
        }
    }

    // public String getMessage() {
    // return message;
    // }

    public void withdraw(Card c, double amount) throws NotEnoughMoneyInAccountException {
        double bal = c.getBalance();

        System.out.println(bal);

        if (c == null)
        throw new IllegalArgumentException("card cannot be null");
        if (amount < 0)
        throw new IllegalArgumentException("please enter amount");
        if (bal > amount)
        throw new NotEnoughMoneyInAccountException("money in account is less");
        else {
            bal = bal - amount;
            c.setBalance(bal);
            System.out.println(bal);
        }
    }

    public void deposit(Card c, double amount) {
        double bal = c.getBalance();

        if (amount == 0)
        throw new IllegalArgumentException("Please enter amount to deposit");
        bal = bal + amount;
        System.out.println(bal);
    }
}


public class Card {
    private double balance;
    private String owner;
    public double getBalance() {
        return balance;
    }
    public void setBalance(double balance) {
        this.balance = balance;
    }
    public String getOwner() {
        return owner;
    }
    public void setOwner(String owner) {
        this.owner = owner;
    }
}

public class NotEnoughMoneyInAccountException extends Exception
{
    public NotEnoughMoneyInAccountException(String m)
    {
        super(m);
    }
}

public class TestATM {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        try
        {
            System.out.println("Starting");
            Card c1 = new Card();
            c1.setOwner("Shweta");
            c1.setBalance(500);

            System.out.println(c1.getOwner());

            ATM atm = new ATM("SBI");
            atm.withdraw(c1, 200);
            atm.deposit(c1, 200);
        }
        catch (NotEnoughMoneyInAccountException e) {
            // TODO Auto-generated catch block
            e.getMessage();
        }

        catch(Exception e)
        {
            e.getMessage();
        }
    }
}

输出是:

Starting
Shweta
Name is   SBI
500.0

当我将 atm 名称(字符串消息)输入为 null 时,应相应地处理异常,但这不会发生。即使我输入要退出的金额 < 0,它也应该进入 if 循环并抛出必须在主程序中处理的异常,也不会发生这种情况。

我也没有得到任何错误。

标签: javachecked-exceptions

解决方案


你的问题在这里:

 catch (NotEnoughMoneyInAccountException e) {
    // TODO Auto-generated catch block
    e.getMessage();
}

catch(Exception e)
{
    e.getMessage(); 
}

e.getMessage();会给你消息,但你不做任何事情。将这些e.getMessage();电话替换为e.printStackTrace();


推荐阅读