Java RPG Boss菜单分页回显异常问题修复咨询
问题修复:Boss菜单分页重复显示问题
问题根源:使用
sc.nextInt()读取玩家操作时,只会读取输入的整数,输入时按下的回车键会作为换行符留在输入缓冲区中。当玩家输入9返回菜单后,外层循环的sc.nextLine()会直接读取这个残留的换行符,导致input为空,触发分页翻页逻辑(currentPage++)。此时外层循环会连续执行两次:先显示第1页(currentPage=0)的5个Boss,接着因为空输入自动翻到第2页(currentPage=1),再次显示5个Boss,最终出现一次性显示10个Boss的异常。修复步骤:在挑战循环的返回菜单逻辑(
usrSelectedIdx == 9的分支)中,break语句前添加一行sc.nextLine(),清除输入缓冲区中残留的换行符,确保外层的sc.nextLine()能正常读取玩家的下一次输入。
修复后的完整代码:
String[] heroArr = {"Alice", "Annie", "Charmander", "Charmeleon", "Charizard", "Bob", "Jack", "Metapod", "Butterfree", "Weedle", "Lily", "Lucy", "Pikachu", "Pidgeotto", "Pidgeot"}; int currentPage = 0; int pageSize = 5; Scanner sc = new Scanner(System.in); while (true) { int startIndex = currentPage * pageSize; int endIndex = Math.min(startIndex + pageSize, heroArr.length); for (int i = startIndex; i < endIndex; i++) { System.out.println(heroArr[i] + "(" + String.valueOf(i + 1) + ")"); } String input = sc.nextLine().trim(); if (input.isEmpty()) { currentPage++; if (endIndex >= heroArr.length) { break; } continue; } else { int heroId = Integer.parseInt(input) - 1; System.out.println("challenge " + heroArr[heroId]); while (true) { System.out.println("challenge begins! choose: 1(attack), 2(escape)"); int usrSelectedIdx = sc.nextInt(); if (usrSelectedIdx == 1) { System.out.println("challenge succeeds! " + heroArr[heroId] + "'s fragment+1"); } else if (usrSelectedIdx == 2) { System.out.println("escaped"); } else if (usrSelectedIdx == 9) { currentPage = 0; sc.nextLine(); // 清除缓冲区残留的换行符 break; } else { System.out.println("error"); } } } }
如果需要避免其他操作(比如攻击、逃跑后继续挑战)出现类似缓冲区问题,也可以在所有sc.nextInt()调用后都添加sc.nextLine(),彻底清除残留的换行符。
内容的提问来源于stack exchange,提问作者singularli
相关产品推荐
相关产品推荐

