如何修改Java的addTeam方法,实现重复输入的正确提示逻辑
修改Java addTeam方法实现指定输入逻辑
需求说明
原addTeam方法逻辑为:请求用户输入团队名称,若名称不存在则加入ArrayList,存在则递归调用自身。现需调整为:
- 仅在首次输入时打印初始提示语句
- 当团队已存在时,打印
团队[名称]已存在!请输入新名称:并重新获取输入 - 不可在方法外新增字段,可使用循环替代递归实现
当前代码
public void addTeam(){ System.out.print("Please enter the name of the team: "); String teamName = In.nextLine(); //In.nextLine() prompts user for String input if (teamExists(teamName) == null){ //teamExists() returns the team object if found else null teams.add(new Team(teamName)); System.out.println("Team " + teamName + " added! "); } else{ System.out.print("Team " + teamName + " already exist! "); addTeam(); } teamsPage(); }
修改后的代码
public void addTeam(){ // 仅打印一次初始提示 System.out.print("请输入团队名称:"); String teamName = In.nextLine(); // 使用循环处理重复输入,避免递归 while (teamExists(teamName) != null) { System.out.printf("团队%s已存在!请输入新名称:", teamName); teamName = In.nextLine(); } // 确认名称不存在后添加团队 teams.add(new Team(teamName)); System.out.printf("团队%s已添加!%n", teamName); teamsPage(); }
改动说明
- 将初始提示语句移至循环外,确保只打印一次
- 用
while循环替代递归,循环判断输入的团队是否存在:- 若存在则打印指定提示并重新获取输入
- 直到输入的名称不存在时退出循环
- 统一将提示语改为中文,符合示例输出要求
- 避免了递归可能导致的栈溢出问题,逻辑更清晰
内容的提问来源于stack exchange,提问作者vishalpd
相关产品推荐
相关产品推荐

