Java中Scanner在for循环运行期间无法完成读取问题求助
问题修复方案
根因说明
Scanner的nextInt()方法仅读取输入的整数值,不会消费整数后跟随的换行符。你将清理换行残留的key.nextLine()放在了for循环内部,导致第一轮循环执行完成后,后续每轮循环都会多执行一次无意义的换行读取,出现假阻塞:
- 第一轮循环:
key.nextLine()先吃掉nextInt()遗留的换行,再正常读取用户输入的文本,流程无异常 - 从第二轮循环开始:首先执行
key.nextLine()时没有残留换行需要清理,程序会停在这里等待输入,你输入的内容会被这行空的nextLine()直接消费,下一行读取文本的key.nextLine()会再次进入等待状态,看起来就像输入没有被处理、程序完全卡住
调整代码
不需要关闭重建Scanner,只需要把消费nextInt()残留换行的key.nextLine()挪到nextInt()执行后、for循环启动前即可,修改后的代码如下:
public static void getInput(Scanner key) { //This method takes the input of the user and makes it usable, controls all other methods, and prints findings System.out.print("\nHow many pieces of text do you want to analyze? "); int textNumb = key.nextInt(); // 仅执行一次即可清理nextInt()遗留的换行符 key.nextLine(); for( int i = 1; i <= textNumb; i++) { System.out.print("\nPlease enter text sample number " + i + ": "); String textInput = key.nextLine(); System.out.print("text has been received\n"); int sentences = getSentences(textInput); int words = getWords(textInput); int syllables = countSyllables(textInput); printResults(sentences,words,syllables,textInput); } }
内容的提问来源于stack exchange,提问作者Keolai
相关产品推荐
相关产品推荐

