Java文本游戏解析器问题

时间:2013-02-20 13:58:27

标签: java text adventure

这是我的第一篇文章,我只是Java的新手,很抱歉,如果它不是最新的。

我一直在用Java编写一个基于文本的冒险游戏,而我的代码在一个地方让我失望 - 解析器。没有错误,它只是不起作用。它接受输入但不做任何事情。它非常简单,看起来像这样:

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);
}

测试方法只是使用if(words.contains("<word>"))在列表中搜索某些单词。

代码有什么问题,如何改进?

2 个答案:

答案 0 :(得分:1)

如何保持数组并使用类似的东西:

    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!"); 
    }
}

您将获得以下输出:

This found!
is found!
an found!
Array found!

如您所见,您根本无需将其转换为List!

答案 1 :(得分:0)

我将如何做到这一点:

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 ();
    }
}

示例会话:

[in]  hello world
[in]  foo bar
[out] Foo!
[in]  foobar bar foobar
[out] Bar!