简体   繁体   中英

Why my Java loop skip the first user input on the first iteration?

This may be very stupid. I am a beginner, but for some reason my for loop will output the two print statements next to each other for the first loop without accepting user input. On the second loop, the loop works properly.

  public static void fleschTest(Scanner key, int numPieces) {
        String textInput = "";
        for(int i = 1; i <= numPieces; i++) {
            System.out.print("\nPlease enter text sample number " + i + ": ");
            textInput = getText(key);
            System.out.println("Statistics for this text: " + textInput);
        }
    }

This is the method being called in fleschTest.

    public static String getText(Scanner key) {
        String textInput = key.nextLine();
        return " " + textInput; 
    }

Current output: if number or text samples is 2. Please enter text sample number 1: Statistics for this text:

Please enter text sample number 2: (user input)

Statistics for this text: (user input)

You can move to the next line after the user input by adding a blank println() statement:

TextInput = getText(key);
//
System.out.println();
//
System.out.println("Statistics for this text: " + textInput);

How did you define your Scanner?? For me, I'm able to get the user input with your code. Below is the code from where I'm calling your fleshchTest method. Try with it, it should work.

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    fleschTest(scanner, 3);
}

Below is my sample output:

Please enter text sample number 1: John
Statistics for this text:  John

Please enter text sample number 2: Doe
Statistics for this text:  Doe

Please enter text sample number 3: Amelia
Statistics for this text:  Amelia

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM