When working on a text based role playing game I wanted a simple way to check for user input. An example of this is as follows:
You enter a small clearing, there is a path north, south and north-west. In the tree line you can also see something shimmering.
user: go north-west
In this case the user wants to go north-west but I would also accept other commands to go in that direction such as: “walk north-west”, “northwest”, “north west”, “go north west”, “go north-west.” The easiest way to properly do this is to pass multiple strings through a method. Naturally you can only have as many strings as declared or you would have to use the alternative of passing an array.
The code to solve this problem goes as follows.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | public boolean check(String... x){ //normally when passing a string it is required to do the following: // String x, but with arguments we can pass it something like this: //check("go north","head north","travel north","north") for(String words : x){ //creates a loop declaring the variable words and loading it with //the value of x if(words.equalsIgnoreCase(input)){ //this checks to see if the word is equal to the users input. return true; // if so then return true } } return false; //after it loops through all of the possibilities it will return false. } |
In order to use this in the way that I have you must know that the variable “input” is loaded from the keyboard. As a matter of fact this method is placed inside of a class called “Input.” This class has a static variable called string, a way to prompt for a string, number, etc and checks the input for errors. An example of this class in action would be something like this:
1 2 3 4 5 6 7 8 | inp1.promptInput(); if(inp1.check("attack","fight","1")){ attack(); }else if(inp1.check("flee","run","2")){ run(); }else{ System.out.println("Please enter a valid command."); } |
The code first asks the user to prompt one of the menu items. calls a method if check returns true or displays an error if there is nothing there.

