2013-05-14 35 views
1

我有一個字符串數組,每個字符串都以"<x> <y>"的形式構建。如果y'n'開始,那麼看起來我的程序無法找到它。在數組中找不到一些值

所以,不工作的字符串是。

"w north", 
"w n", 
"walk n", 
"walk north" 

你能幫忙解釋一下爲什麼嗎?

string[] next = { "next", "ne", "nx", "nxt" }; 
string[] yes = { "yes", "y" }; 
string[] no = { "no", "n" }; 
string[] clear = { "clear", "c" }; 
string[] help = { "help", "h" }; 
string[] walk = 
     { 
      "w north", 
      "w south", 
      "w west", 
      "w east", 
      "w n", 
      "w s", 
      "w w", 
      "w e", 
      "walk north", 
      "walk south", 
      "walk west", 
      "walk east" , 
      "walk n", 
      "walk s", 
      "walk w", 
      "walk e" 
     }; 

//Checks if any input match the arrays 
public string Input(string input) 
{ 
    input = input.ToLower(); 
    if (next.Any(input.Contains)) 
    { 
     return "next"; 
    } 
    else if (yes.Any(input.Contains)) 
    { 
     return "yes"; 
    } 
    else if (no.Any(input.Contains)) 
    { 
     return "no"; 
    } 
    else if (clear.Any(input.Contains)) 
    { 
     return "clear"; 
    } 
    else if (help.Any(input.Contains)) 
    { 
     return "help"; 
    } 
    else if (walk.Any(input.Contains)) 
    { 
     MessageBox.Show("test input"); 
     Location C_locations = new Location(); 
     C_locations.Change_location(input); 
     return "walk"; 
    } 
    else 
    { 
     return "not found"; 
    } 
} 

的字符串:"w north""w n""walk n""walk north",應該運行這部分代碼:

else if (walk.Any(input.Contains)) 
{ 
    MessageBox.Show("test input"); 
    Location C_locations = new Location(); 
    C_locations.Change_location(input); 
    return "walk"; 
} 
+0

如果您在提交前完全充實您的問題,這將有助於獲得正確的答案並防止任何關閉。 – Jodrell 2013-05-14 16:33:44

回答

4

的原因,你的代碼不工作是在你的no陣列的內容:它包含一個單字母字符串"n"。正是這種字符串,使

no.Any(input.Contains) 

評估,以True爲包含字母'n'任何輸入字符串。

爲了解決此問題,您可以將支票walk移動到if/then/else鏈的頂部。但是,解決方案不會過於穩健:"yellow"將被分類爲"yes","cat"將變爲"clear",依此類推。