【问题标题】:Compare string to 2 other strings将字符串与其他 2 个字符串进行比较
【发布时间】:2014-08-02 09:15:26
【问题描述】:

所以我有这个代码部分:

        private int checkErrors() {
           int error = 0;
           if (!(nether.Text.Equals("true"))) { error += 1; }
           if (!(nether.Text.Equals("false"))) { error += 1; }
           if (!(fly.Text.Equals("true"))) { error += 1; }
           if (!(fly.Text.Equals("false"))) { error += 1; }
           if (!(achivments.Text.Equals("true"))) { error += 1; }
           if (!(achivments.Text.Equals("false"))) { error += 1; }
           if (!(whitelist.Text.Equals("true"))) { error += 1; }
           if (!(whitelist.Text.Equals("false"))) { error += 1; }
           if (!(pvp.Text.Equals("true"))) { error += 1; }
           if (!(pvp.Text.Equals("false"))) { error += 1; }
           if (!(commandBlock.Text.Equals("true"))) { error += 1; }
           if (!(commandBlock.Text.Equals("false"))) { error += 1; }
           if (!(spawnMonster.Text.Equals("true"))) { error += 1; }
           if (!(spawnMonster.Text.Equals("false")) { error += 1; }
           return error;
        }

但无论如何它会让我知道'error = 7',因为当一个陈述为真时,另一个陈述为假 所以我的问题是:

有没有办法将两个字符串与第三个字符串进行比较?

其他示例:我有字符串userInput,如果userInput 不等于"a""b" 则执行error += 1;

【问题讨论】:

  • 我在猜测.. 你的意思是 Text 可以是 true 或者是 false 如果不是 error += 1
  • “有没有办法将 2 个字符串与第三个字符串进行比较?”这一行是什么意思。
  • 我有 2 个固定字符串,想将它们与变量第三个字符串进行比较

标签: c# if-statement compare


【解决方案1】:

我怀疑你试图找出它不是“真”并且它不是“假”的情况。所以像:

if (spawnMonster.Text != "true" && spawnMonster.Text != "false")
{
    error++;
}

或者,表达条件一次,并将其应用于所有字符串:

var strings = new[] { nether.Text, fly.Text, achivments.Text, whitelist.Text
                      pvp.Text, commandBlock.Text, spawnMonster.Text };
return strings.Count(t => t != "true" && t != "false");

【讨论】:

    【解决方案2】:

    只有两个子句:

              if (!nether.Text.Equals("true") && !nether.Text.Equals("false")) { error += 1; }
    

    【讨论】:

      【解决方案3】:

      您可以使用的另一种方法是创建一个接受 2 个参数的函数。一个参数是 userInput,另一个参数是 userInput 不应该的值数组。它将返回 1 或 0。

      例子:

      public int isBadValue(string userInput, string[] goodValues){
        if(Array.IndexOf(userInput) > -1){
             return 0;
        }
      
        return 1;
      }
      

      在你的代码中你可以这样做:

      string[] goodValues = {"a", "b"};
      error += isBadValue("s", goodValues);
      

      您可以轻松添加更多好的值,并且该函数将能够处理它。不确定好值是否会根据输入字段发生变化,这就是我没有将其包含在 isBadValue 函数中的原因。

      【讨论】:

        猜你喜欢
        • 2018-05-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-09-02
        • 1970-01-01
        • 2017-02-20
        相关资源
        最近更新 更多