这是我的第一篇文章,而且我只是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>"))在列表中搜索某些单词。

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

===============>>#1 票数: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!

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

===============>>#2 票数: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!

  ask by SamBrev translate from so

未解决问题?本站智能推荐: