数据驱动 vs 分支硬编码

数组只装功能项、"退出"单独打印,还用了增强 for 循环(for (String menu : MENU))

/**
复制代码
* 用switch实现平台主菜单:1-装修报价 2-找师傅 3-找公司 0-退出系统,打印选择结果 * <p> * 注意: * 1、main方法是static,只能调用static属性 * 2、if...else语句 * 3、Scanner的使用 * 4、边界判断 * 5、for循环 * 6、while循环 * 7、数组 * 8、switch语句 * */ import java.util.Scanner; public class Day10PlatformMainMenu { private static final String[] MENU = {"1 - 装修报价", "2 - 找公司", "3 - 找设计", "4 - 找师傅"}; public static void main(String[] args) { System.out.printf("%n----------------装修服务平台主菜单----------------%n"); for (String menu : MENU) { System.out.println(menu); } System.out.println("0 - 退出系统"); Scanner in = new Scanner(System.in); while (true) { System.out.print("请输入菜单的序号【0-退出系统】:"); int selectedMenuItem = in.nextInt(); if (selectedMenuItem == 0) { break; } if (selectedMenuItem >0 && selectedMenuItem <= 4) { String selectedMenuItemDesc = switch (selectedMenuItem){ case 1 -> "进入【1 - 装修报价】……"; case 2 -> "进入【2 - 找公司】……"; case 3 -> "进入【3 - 找设计】……"; case 4 -> "进入【4 - 找师傅】……"; default -> "【错误的选择!】"; }; System.out.println(selectedMenuItemDesc); } else { System.out.println("【错误的输入!】"); continue; } } } }
0个评论
点击登录,快来和大家讨论吧~
表情
图片
暂无评论
下载 APP