Netbeans开发的卡牌游戏在控制台运行重复输出问题排查
控制台输出重复两次问题排查与解决
问题描述
在Netbeans开发的小型卡牌游戏,Netbeans内运行时一切正常,但在Windows CMD控制台构建测试时,用户输入操作前的所有提示内容会重复输出两次。尝试使用scanner.nextLine()和scanner.next()获取输入,问题都未解决。
问题代码片段
while(!turnFinished){ System.out.println(player);//Display the rack System.out.println("Here is the discard pile card " + discard.peek());//Display the top card in the discard pile // 注:原代码此处缺少右括号,已修正 System.out.println("If you want the discard pile card press y or press n to pick up a new card from the draw pile."); String pickup = scanner.nextLine().trim().toLowerCase(); switch(pickup){ case "y","yes" -> { player.drawCardFromDiscard(discard, player, drawPile);//If player decided to pick up from the discard pile turnFinished = true; } case "n","no" -> { player.drawCardFromDeck(drawPile, discard, player, false);//If player decided to pick up from the draw pile turnFinished = true; } } }
排查与解决建议
- 确保Scanner仅初始化一次:检查整个代码中是否多次创建
Scanner实例(比如在循环内、被调用的方法里重复new Scanner(System.in)),多个Scanner会同时监听标准输入流,导致输出逻辑被触发多次。建议在类级别或程序入口处只初始化一次Scanner。 - 处理输入流残留换行符:如果之前使用过
scanner.nextInt()、scanner.nextDouble()这类不读取换行符的方法,输入流中会残留换行符,后续nextLine()会读取到空字符串,导致循环重复执行。解决方式是在这类方法后添加scanner.nextLine()清空换行符。 - 检查
turnFinished变量逻辑:确认该变量是否在某些分支中被意外重置为false,导致循环重复执行输出内容。 - 排查自定义方法的输出逻辑:检查
player.toString()(即System.out.println(player)调用的内容)、discard.peek()以及drawCardFromDiscard/drawCardFromDeck方法内部是否存在额外的输出语句,导致内容重复。
内容的提问来源于stack exchange,提问作者Papers2
相关产品推荐
相关产品推荐

