1

这是我的第一篇文章,我只是 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>"))

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

4

2 回答 2

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!

如您所见,您根本不需要将其转换为列表!

于 2013-02-20T14:12:32.230 回答
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!
于 2013-02-20T14:11:25.547 回答