简体   繁体   English

Java文字游戏解析器问题

[英]Java text game parser problems

This is my first post, and I'm only new to Java, so sorry if it is not up to scratch. 这是我的第一篇文章,而且我只是Java的新手,如果还不成熟,对不起。

I have been writing a text-based adventure game in Java, and my code has failed me in one place - the parser. 我一直在用Java编写基于文本的冒险游戏,而我的代码却使我在一个地方失败了-解析器。 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>")) . 测试方法只是使用if(words.contains("<word>"))在列表中搜索某些单词。

What is wrong with the code and how can I improve it? 代码有什么问题,我该如何改进?

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! 如您所见,您根本不需要将其转换为列表!

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!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM