Java ATM机应用NoSuchElementException错误及循环输入修复求助
修复ATM机应用中的NoSuchElementException异常
问题场景
正在学习Java并开发ATM机应用,需求是循环询问用户What would you like to do,直到用户输入有效的操作(仅支持Withdraw和Deposit)。当前代码中,无效输入会正常循环提示Please select a valid choice,但执行一次有效操作后会抛出NoSuchElementException(无此元素异常),无法继续循环。
错误原因
核心问题是重复创建并关闭Scanner实例:
- 在
App类中已经创建了关联System.in的Scanner对象 - 在
Transactions类的Withdrawal()和Deposit()方法中,又各自新建Scanner实例,并在方法结束时调用scanner.close() - 关闭Scanner会同时关闭底层的
System.in输入流,后续App类中的Scanner尝试读取输入时,因输入流已关闭,直接抛出NoSuchElementException
另外原代码存在拼写错误:System.out.println("What woul you like to do?") 中的woul应为would。
修复方案
- 统一使用一个Scanner实例,通过参数传递给
Transactions的方法 - 移除
Transactions方法内的Scanner创建与关闭逻辑 - 修正拼写错误
- 优化
Transactions实例创建逻辑,避免每次循环重置余额
修改后的代码
App.java
import java.util.Scanner; public class App { public static void main(String[] args) throws Exception { Scanner scanner = new Scanner(System.in); boolean done = false; // 仅创建一次Transactions实例,保证余额持续更新 Transactions newTransaction = new Transactions(); while(!done) { System.out.println("What would you like to do?"); String response = scanner.next().toLowerCase(); if (response.equals("withdraw")) { newTransaction.Withdrawal(scanner); } else if (response.equals("deposit")) { newTransaction.Deposit(scanner); } else { System.out.println("Please select a valid choice"); } } scanner.close(); } }
Transactions.java
import java.util.Scanner; public class Transactions { private int currentBalance = 100; public void Withdrawal(Scanner scanner) { System.out.println("How much would you like to withdraw?"); int withdrawAmount = scanner.nextInt(); if (withdrawAmount > 0) { currentBalance -= withdrawAmount; System.out.println("Amount withdrawn: $" + withdrawAmount); System.out.println("Current Balance: $" + Balance()); if (currentBalance < 0) { System.out.println( "You have withdrawn more than you have in current balance.\nYou will be charged a overdraft fee"); } } else { System.out.println("Can't remove 0 or negative amount from account"); } } public void Deposit(Scanner scanner) { System.out.println("How much would you like to deposit?"); int depositAmount = scanner.nextInt(); if (depositAmount > 0) { currentBalance += depositAmount; } System.out.println("Amount deposited: $" + depositAmount); System.out.println("Current Balance: $" + Balance()); } public int Balance() { return currentBalance; } }
内容的提问来源于stack exchange,提问作者Brian Gomez
相关产品推荐
相关产品推荐

