MatAff
MatAff

Reputation: 1333

Java Scanner in Loop only gets first input

I'm trying to get multiple inputs from the user using a for loop. Within that loop I'm calling a function that includes a scanner. The program works fine when I call the function just once. But within a loop only the first time the function is called it works correctly. I've created a simplified example of the program below. How can I change this so the other iterations of the loop also work correctly?

import java.util.Scanner;

public class Main {

public static void main(String[] args) {

    String response = "";

    for(int inputNr = 0; inputNr <=2; inputNr++) {
        response = getResponse();
        System.out.println(response);
    }

}

public static String getResponse() {

    String response = "";

    System.out.println("Enter a String");

    Scanner userInput = new Scanner(System.in);
        if(userInput.hasNextLine()) {
            response = userInput.nextLine();
        }
    userInput.close();

    return response;
}
}

The result looks like

Enter a String
This is what I entered...
This is what I entered...
Enter a String

Enter a String

Upvotes: 0

Views: 1323

Answers (1)

M A
M A

Reputation: 72884

You're closing the Scanner object which is linked to the standard input stream System.in. This causes System.in to close and therefore no more input is accepted. On the next iteration userInput.hasNextLine() returns false. Create a single instance of Scanner and close it after all iterations of the loop are run.

private static Scanner userInput = new Scanner(System.in);

public static void main(String[] args) {

    String response = "";

    for (int inputNr = 0; inputNr <= 2; inputNr++) {
        response = getResponse();
        System.out.println(response);
    }

    userInput.close();
}

public static String getResponse() {

    String response = "";

    System.out.println("Enter a String");

    if (userInput.hasNextLine()) {
        response = userInput.nextLine();
    }

    return response;
}

Upvotes: 2

Related Questions