残留回车 ✅、空输入拦截 ✅、重名计数 ✅
▼/**复制代码* 师傅姓名数组(容量10):实现添加、按名字查找、列出全部,命令行交互操作 * <p> * 注意: * 1、for循环 * 2、常量 * 3、数组 * 4、nextInt 后紧跟 nextLine 会读到空串,后补 in.nextLine() 清残留回车 * 5、null 检查必须在 equals 之前 * */ import java.util.Scanner; public class Day16TradesmanManager { public static final String[] MENU = {"【1 - 增加姓名】", "【2 - 按名字查找】", "【3 - 列出全部】", "【0 - 退出】"}; public static void main(String[] args) { String[] tradesMan = new String[10]; int size = 0; // 初始化为0,每增加一个师傅,就+1 Scanner in = new Scanner(System.in); while (true) { System.out.printf("%n%n--------------------装修师傅管理系统--------------------"); // 显示菜单 for (String item : MENU) { System.out.printf("%n %s", item); } System.out.printf("%n%n请输入您的选择【0 - 退出】:"); int selectedItem = in.nextInt(); in.nextLine(); if (selectedItem == 0) { break; } else { switch (selectedItem) { // 增加姓名 case 1: { if (size < tradesMan.length) { System.out.printf("%n%n请输入姓名:"); String nameInput = in.nextLine().trim(); // TODO:判断键盘的输入是否为空、字符串长度、是否确定增加、是否还要增加 if (nameInput.isEmpty()) { System.out.printf("%n%n无效输入!"); } else { tradesMan[size] = nameInput; size++; } } else { System.out.printf("%n%n数据已填满,无法再增加!"); } break; } // 按姓名查询 case 2: { System.out.printf("%n%n--------------------按姓名查找--------------------"); // 先判断数组是否有数据 if (size > 0) { System.out.printf("%n%n请输入要查找的姓名:"); String targetName = in.nextLine().trim(); int foundCount = 0; // 姓名可能有重名,查找到第一个后还有继续查找 // TODO:判断键盘的输入是否为空 for (String name : tradesMan) { if (name == null) { continue; } if (name.equals(targetName)) { System.out.printf("%n%n查找的姓名是:%s", name); foundCount++; } } if (foundCount == 0) { System.out.printf("%n%n没有找到姓名!"); } } else { System.out.printf("%n%n没有数据,不能查询!"); } break; } // 列出全部 case 3: { System.out.printf("%n%n---------------------列出全部--------------------"); if (size == 0) { System.out.printf("%n%n没有可展示的数据!"); } else { // 使用for-i循环,步数会少一点 for (int i = 0; i < size; i++) { if (tradesMan[i] != null) { System.out.printf("%n%s", tradesMan[i]); } } } break; } default: { System.out.printf("%n%n无效的输入!"); break; } } } } } }
评论
问答助学
相关内容
0个评论
全部评论
点击登录,快来和大家讨论吧~
表情
图片
暂无评论
