簡體   English   中英

Java文字游戲解析器問題

[英]Java text game parser problems

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

代碼有什么問題,我該如何改進?

如何保留數組並使用類似這樣的東西:

    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!

如您所見,您根本不需要將其轉換為列表!

這是我的處理方式:

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!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM