Reputation: 1
This is my first post, and I'm only new to Java, so sorry if it is not up to scratch.
I have been writing a text-based adventure game in Java, and my code has failed me in one place - the parser. There is no error, it just doesnt work. It takes in the input but does nothing about it. It is very simple, and looks something like this:
public static void getInput(){
System.out.print(">>"); //print cue for input
String i = scan.nextLine(); //get (i)nput
String[] w = i.split(" "); //split input into (w)ords
List words = Arrays.asList(w); //change to list format
test(words);
}
The test method just searches the list for certain words using if(words.contains("<word>"))
.
What is wrong with the code and how can I improve it?
Upvotes: 0
Views: 485
Reputation: 9
How about keeping the array and using something like this:
String[] word_list = {"This","is","an","Array"}; //An Array in your fault its 'w'
for (int i = 0;i < word_list.length;i++) { //Running trough all Elements
System.out.println(word_list[i]);
if (word_list[i].equalsIgnoreCase("This")) {
System.out.println("This found!");
}
if (word_list[i].equalsIgnoreCase("is")) {
System.out.println("is found!");
}
if (word_list[i].equalsIgnoreCase("an")) {
System.out.println("an found!");
}
if (word_list[i].equalsIgnoreCase("Array")) {
System.out.println("Array found!");
}
if (word_list[i].equalsIgnoreCase("NotExistant")) { //Wont be found
System.out.println("NotExistant found!");
}
}
You will get the following output:
This found!
is found!
an found!
Array found!
As you can see you needn't convert it to a List at all!
Upvotes: 1
Reputation: 13890
Here is how I would do this:
public class ReadInput {
private static void processInput (List <String> words)
{
if (words.contains ("foo"))
System.out.println ("Foo!");
else if (words.contains ("bar"))
System.out.println ("Bar!");
}
public static void readInput () throws Exception
{
BufferedReader reader =
new BufferedReader (
new InputStreamReader (System.in));
String line;
while ((line = reader.readLine ()) != null)
{
String [] words = line.split (" ");
processInput (Arrays.asList (words));
}
}
public static void main (String [] args) throws Exception
{
readInput ();
}
}
Sample session:
[in] hello world
[in] foo bar
[out] Foo!
[in] foobar bar foobar
[out] Bar!
Upvotes: 0