2013-05-14 34 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",依此类推。