首页 > 解决方案 > 扫描器在 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(); 
        
    for( int i = 1; i <= textNumb; i++) {
        System.out.print("\nPlease enter text sample number " + i + ": "); 
            
        key.nextLine(); 
        String textInput = key.nextLine();
            
        System.out.print("text has been received\n");   //this does not print after first round
            
        int sentences = getSentences(textInput); 
        int words = getWords(textInput); 
        int syllables = countSyllables(textInput); 
            
        printResults(sentences,words,syllables,textInput); 
    }
}

在第一轮 for 循环之后,扫描仪卡住并且程序完全暂停。如果我在第一轮后输入文本后再次按 Enter,则其余方法实际上都不会处理任何文本。在不关闭并重新打开扫描仪的情况下如何解决此问题?谢谢你。

标签: javafor-loopjava.util.scanner

解决方案


key.nextLine()我假设在没有分配变量的情况下额外调用是因为您可能遇到了这里描述的问题: Scanner is skipping nextLine() after using next() or nextFoo()?

但是,在实施那里描述的解决方法时,您必须考虑到您正在使用循环。记住这一点,你只需要nextInt()在循环之后和之后读取换行符一次,额外的没有意义nextLine()。所以片段应该是:

int textNumb = key.nextInt();
key.nextLine(); // consume newline once, outside the loop

for (int i = 1; i <= textNumb; i++) {
    System.out.print("\nPlease enter text sample number " + i + ": "); 
    String textInput = key.nextLine(); // read input inside the loop
    ...
}

推荐阅读