0

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

1 Answer 1

2

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.