-2

I am attempting to write some code that analyzes several pieces of text, but I found an issue with the scanner method. Here is my relevant code:

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); 
    }
}

After the first round of the for loop, the scanner gets stuck and the program pauses completely. If I hit enter again after entering my text after the first round, none of the text actually gets processed by the rest of the methods. What can I do to fix this without closing and re-opening the scanner? Thank you.

AmrDeveloper
  • 3,826
  • 1
  • 21
  • 30
Keolai
  • 19
  • 1
  • 7
  • 2
    You have an extra `readLine()` presumably to skip over the rest of the line following your `nextInt()`. But you only do the `nextInt` once; you don't need the extra `readLine()` inside your loop. Move it to before the loop. – khelwood Oct 04 '21 at 13:38

1 Answers1

0

I assume the extra call to key.nextLine() without an assignment to a variable is because you probably encountered the issue described here: Scanner is skipping nextLine() after using next() or nextFoo()?

However, when implementing the workaround described there, you have to consider that you are using a loop. Keeping that in mind, you will only have to read the newline once after the nextInt() and after that in the loop, there is no point for the extra nextLine(). So the snippet should be:

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
    ...
}
maloomeister
  • 2,461
  • 1
  • 12
  • 21