文本类Java游戏代码执行中断求助:无法正常进入山区场景
问题分析与解决方案
问题根源
问题出在Scanner的输入处理逻辑上:nextInt()方法仅读取输入的整数部分,不会处理用户输入数字后按下的换行符。当猜数字游戏结束后,后续调用nextLine()时,会直接读取缓冲区中残留的换行符,导致input为空字符串,触发山区路径选择环节的default分支,直接输出无效输入提示。
修复方案
在playRandomNumberGuesser方法的循环结束后,添加一行userInput.nextLine(),清除输入缓冲区中残留的换行符,确保后续的nextLine()能正确等待用户输入。
修改后的playRandomNumberGuesser方法
public static void playRandomNumberGuesser(int min, int max, Scanner userInput) { Random random = new Random(); int randomNumber = random.nextInt((max - min) + 1) + min; int guess; boolean guessedCorrectly = false; do { System.out.print("Enter your guess (" + min + "-" + max + "): "); guess = userInput.nextInt(); if (guess < min || guess > max) { System.out.println("Please enter a number between " + min + " and " + max + "."); } else if (guess < randomNumber) { System.out.println("Too low. Try again."); } else if (guess > randomNumber) { System.out.println("Too high. Try again."); } else if (guess == randomNumber) { System.out.println("[OLD MAN] 'Well done!! you've done well'\n" + "[OLD MAN] 'You really do have a knack for these games. I'll tell you that. Here, take this for your journey.'\n"); guessedCorrectly = true; } } while (!guessedCorrectly); // 清除输入缓冲区中的残留换行符 userInput.nextLine(); }
补充优化方案
如果后续还有混合使用nextInt()和nextLine()的场景,也可以统一用nextLine()读取所有输入,再将需要转为数字的内容用Integer.parseInt()转换,从根源避免换行符残留问题,示例如下:
// 替换原有的guess = userInput.nextInt(); String guessStr = userInput.nextLine(); try { guess = Integer.parseInt(guessStr); } catch (NumberFormatException e) { System.out.println("Please enter a valid number."); continue; }
内容的提问来源于stack exchange,提问作者al.erceg
相关产品推荐
相关产品推荐

