为何我的Java代码持续输出无限个Current Balance: 0并触发栈溢出错误?
问题核心分析
你的代码触发无限递归,最终导致StackOverflowError,具体问题点如下:
displayBalance方法:第12行return displayBalance(balance);会无终止地调用自身,一执行就无限输出Current Balance: 0,直到栈内存耗尽。amountWithdrawing方法:同样存在无限递归,return amountWithdrawing(balance, withdrawAmount);没有任何取款逻辑就反复调用自己,永远无法返回结果。- 静态成员设计错误:
balance被定义为static,导致所有账户实例共享同一个余额,违背了每个账户独立管理余额的原则。 - 构造函数未生效:接收了账户名和初始金额参数,但完全没用来初始化余额,只是打印了一句无关的话。
- 实例打印问题:直接输出
usAccount和chAccount时,会打印对象的默认内存地址,而非账户余额。
修复后的完整代码
package sct; public class Account { // 移除static,每个账户拥有独立余额 private int balance; private String accountName; // 新增账户名属性,区分不同账户 // 构造函数初始化账户信息 public Account(String accountName, double initialBalance) { this.accountName = accountName; this.balance = (int) initialBalance; // 按原代码逻辑转int,若需保留小数可改为double类型 System.out.println(accountName + " 初始化完成,初始余额: " + this.balance); } // 移除递归,直接打印当前账户余额 public void displayBalance() { System.out.println(accountName + " 当前余额: " + balance); } // 实现取款逻辑,添加合法性校验 public int amountWithdrawing(int withdrawAmount) { if (withdrawAmount > 0 && withdrawAmount <= balance) { balance -= withdrawAmount; System.out.println(accountName + " 取款金额: " + withdrawAmount); } else { System.out.println(accountName + " 取款失败:金额无效或余额不足"); } return balance; } // 优化存款逻辑,添加合法性校验 public int amountDepositing(int depositAmount) { if (depositAmount > 0) { balance += depositAmount; System.out.println(accountName + " 存款金额: " + depositAmount); } else { System.out.println(accountName + " 存款失败:金额无效"); } return balance; } public static void main(String[] args) { // 创建两个独立的账户实例 Account usAccount = new Account("US account", 100.00); Account chAccount = new Account("Swiss account", 1000000.00); System.out.println("\n=== 开始操作 ==="); // 操作US账户取款20 usAccount.amountWithdrawing(20); // 操作瑞士账户存款200 chAccount.amountDepositing(200); System.out.println("\n=== 最终余额 ==="); usAccount.displayBalance(); chAccount.displayBalance(); } }
关键修改说明
- 移除所有不必要的
static修饰符,让每个Account实例拥有独立的余额和账户名,符合面向对象设计。 - 修复两个方法的无限递归问题,添加了合理的取款/存款业务逻辑和参数校验。
- 让构造函数真正起到初始化账户信息的作用,不再是空架子。
- 调整
main方法逻辑,直接操作账户实例,清晰展示每个账户的独立操作和结果。
内容的提问来源于stack exchange,提问作者Ness
相关产品推荐
相关产品推荐

