TheFaceOfBoe
TheFaceOfBoe

Reputation: 63

Design Pattern in Java for Getting Input and Acting on it

I'm trying to make a tic-tac-toe game and I'm encountering a lot of copy-paste work for inputs. I'm trying to figure out what design pattern and implementation works for prompting the user, collecting their input, comparing it and then acting by assigning a value. Right now my code looks like this.

public void promptPlayerCount(BufferedReader in) throws IOException {
    String  input;

    // initial prompt
    System.out.println("How many players?");
    input = "try again";
    while (input.equals("try again")) {
        input = in.readLine();
        // extract data and check it
        switch (Integer.parseInt(input)) {
            case 1:
                // assignment
                playerCount = 1;
                break;
            case 2:
                playerCount = 2;
                break;
            default:
                input = "try again";
                // clarified instructions
                System.out.println("please enter 1 or 2");
        }
    }
}

There's a part of me that thinks I could make a function (maybe a factory?) that allows me to generate a function by passing the constructing function the details of the initial prompt, the extraction method, the assignment action and the clarification message.

Would this be best done with lambda functions?

Upvotes: 2

Views: 130

Answers (1)

Bill K
Bill K

Reputation: 62789

Text input is hard, especially if you can't trust your user (like in a game). Your parseInt will throw a nasty exception right off if your value isn't an integer.

Also standard in is not friendly. I assume this is for an assignment so I won't fault you for using it, but in anything where you don't HAVE to use stdin, don't. The problem is that it's amazingly difficult to get Java to respond to anything less than an entire line with an enter at the end.

When dealing with user input I almost always trim it (Just because they love to insert random white spaces at the beginnings and end) and check to see if it's empty. This could probably be put into a function that also either shows an error or exits the program on "Empty" and otherwise returns a string.

If you often want int values, write a second function that calls the first. Have the second function return an int, but have it catch the exception if the text is invalid and prompt the user again. You could even have this function take a "Range" of integers as a parameter and provide a prompt. So what you have above could look like this:

playerCount = getUserInput("Please enter the number of users", 1, 2);

The rest is wrapped in simple non-redundant functions.

Won't write the code for you because A) it's probably a homework assignment and the fun part is actually coding it and B) someone else probably will provide a full solution with code before I'm done typing this :(

Good luck.

Upvotes: 1

Related Questions