Java中用switch实现程序入口选择生效却不明原因,求解析
程序启动选项的执行逻辑解析
我想在程序启动时添加进入管理员端或前端商城的选项,加了switch-case后功能立刻生效了,但我搞不懂原因。选选项2进入前端商城时直接就进去了,我本来以为得写对应的方法才行。有人能解释下我代码开头的具体执行逻辑吗?感觉自己是碰巧实现的功能。
public static void main(String[] args) throws IOException { while (true) { System.out.println("Login to Admin site (1) or go to store front (2)?"); int choice = scnr.nextInt(); switch (choice) { case 1: StoreFront server = new StoreFront(0); server.start(6666); case 2: } inventoryManager.initializeInventoryFromFile("inventory.json"); System.out.println("Welcome to the Game Store \n"); System.out.println("Please select an option from the menu"); System.out.println("***************************************"); System.out.println("************MAIN MENU ******************\n"); while (true) { System.out.println("Enter one of the following:\n\n" + "'1' : View Products\n" + "'2' : Purchase Products\n" + "'3' : Return Products\n" + "'4' : Exit"); int menuChoice = scnr.nextInt(); switch (menuChoice) { case 1: viewProducts(); break; case 2: purchaseProducts(); break; case 3: returnProducts(); break; case 4: System.out.println("Thank you for coming by. Please come again."); System.exit(0); break; default: System.out.println("INVALID OPTION. Please select an option 1-4"); scnr.close(); } // server.cleanUp(); } } }
核心逻辑解析
你的功能能“碰巧”生效,本质是switch-case的穿透特性在起作用——你写的switch里没有加break语句:
选择选项2时:
程序进入case 2,但这个分支里没有任何代码,执行完后直接跳出switch,接着执行后面的商城初始化(inventoryManager.initializeInventoryFromFile)和主菜单循环代码,自然就进入了前端商城。选择选项1时:
程序先执行管理员端的启动代码(server.start(6666)),但因为case 1末尾没有break,程序会直接“穿透”到case 2,执行完空的case 2后跳出switch,同样会执行后面的商城代码——这其实是个bug,意味着你选管理员端时,会同时启动管理员服务和进入前端商城,这大概率不是你想要的效果。
问题修正建议
- 在
case 1的末尾添加break;,避免穿透到case 2:case 1: StoreFront server = new StoreFront(0); server.start(6666); break; // 加上这个,选1时就不会执行后面的商城代码 case 2: // 这里可以留空,或者添加商城专属的初始化逻辑 break; - 如果管理员端是独立的运行流程,启动后应该让程序停留在管理员逻辑里,或者提供退出后回到选择界面的机制,而不是直接执行商城代码。
内容的提问来源于stack exchange,提问作者Mitchell
相关产品推荐
相关产品推荐

