Java新手求助:如何让主类调用子类BankAccount的menu方法正常运行?
问题原因与解决方法
你的代码核心问题是BankAccount类的menu()方法未完成:只写了开头的部分菜单输出,缺少完整的选项列表、用户输入处理逻辑、功能调用代码,甚至连方法和类的闭合大括号都没有,导致程序执行到一半就结束,无法显示完整菜单或执行后续功能。
修正后的完整代码
import java.util.Scanner; public class BankApplication { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter your 'Name' and 'CustomerId' to access your Bank account:"); String name = sc.nextLine(); String customerId = sc.nextLine(); BankAccount obj1 = new BankAccount(name, customerId); obj1.menu(); } } class BankAccount { double bal; double prevTrans; String customerName; String customerId; BankAccount(String customerName, String customerId) { this.customerName = customerName; this.customerId = customerId; } void deposit(double amount) { if (amount != 0) { bal += amount; prevTrans = amount; System.out.println("Successfully deposited: " + amount); } else { System.out.println("Invalid deposit amount"); } } void withdraw(double amt) { if (amt != 0 && bal >= amt) { bal -= amt; prevTrans = -amt; System.out.println("Successfully withdrawn: " + amt); } else if (bal < amt) { System.out.println("Bank balance insufficient"); } else { System.out.println("Invalid withdrawal amount"); } } void getPreviousTrans() { if (prevTrans > 0) { System.out.println("Deposited: " + prevTrans); } else if (prevTrans < 0) { System.out.println("Withdrawn: " + Math.abs(prevTrans)); } else { System.out.println("No transaction occurred"); } } void menu() { char option; Scanner sc = new Scanner(System.in); do { System.out.println("\nWelcome " + customerName); System.out.println("Your ID: " + customerId); System.out.println("\n===== Bank Menu ====="); System.out.println("a) Check Balance"); System.out.println("b) Deposit Money"); System.out.println("c) Withdraw Money"); System.out.println("d) View Previous Transaction"); System.out.println("e) Exit"); System.out.print("Enter your option: "); option = sc.next().charAt(0); switch (option) { case 'a': case 'A': System.out.println("Current Balance: " + bal); break; case 'b': case 'B': System.out.print("Enter amount to deposit: "); double depositAmt = sc.nextDouble(); deposit(depositAmt); break; case 'c': case 'C': System.out.print("Enter amount to withdraw: "); double withdrawAmt = sc.nextDouble(); withdraw(withdrawAmt); break; case 'd': case 'D': getPreviousTrans(); break; case 'e': case 'E': System.out.println("Thank you for using our bank services!"); break; default: System.out.println("Invalid option, please try again"); } } while (option != 'e' && option != 'E'); sc.close(); } }
关键修正点
- 补全完整菜单选项,用
do-while循环实现菜单持续显示,直到用户选择退出 - 添加
switch语句处理用户输入,调用对应的deposit、withdraw等功能方法 - 补全所有缺失的大括号,修复语法错误
- 给
deposit和withdraw方法添加无效输入提示,增强用户体验 - 支持大小写选项输入,提升易用性
内容的提问来源于stack exchange,提问作者grzurmum
相关产品推荐
相关产品推荐

