java - 带有异常处理的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 循环并抛出必须在主程序中处理的异常,也不会发生这种情况。
我也没有得到任何错误。
解决方案
你的问题在这里:
catch (NotEnoughMoneyInAccountException e) {
// TODO Auto-generated catch block
e.getMessage();
}
catch(Exception e)
{
e.getMessage();
}
e.getMessage();
会给你消息,但你不做任何事情。将这些e.getMessage();
电话替换为e.printStackTrace();
推荐阅读
- firebase-authentication - 通过 GCP 身份平台将 okta 用作 IdP 时如何从 okta 获取用户数据?
- c++ - 教程中旧代码中范围解析运算符的问题
- python - 添加的类如何使用主类的属性?
- c# - 注册用户无法登录asp.net身份
- sql - SQL 中的字符串到日期
- git - Git子模块:如何知道子模块的提交/标签
- python - ubuntu环境下使用python将ppt转换为视频
- python - 如何写入文件然后在 Python 中读取文件
- xml - XSLT - 如何在 XML 的同一行中使用多个键求和
- postgresql - 如何聚合postgresql中一列的所有数字?