计算字符串以确保输入在最小/最大边界内

时间:2017-10-19 18:50:13

标签: c#

对于我项目的一部分,我想强制执行用户输入只能在最小/最大字边界内的规则。最少1个单词,最多50个单词。布尔值不会从默认设置值false更改。这是我的代码:

 bool WordCount_Bool = false;

        //Goto the method that handles the calculation of whether the users input is within the boundary.
        WordCount_EH(WordCount_Bool);
        //Decide whether to continue with the program depending on the users input.
        if (WordCount_Bool == true)
        {
            /*TEMP*/MessageBox.Show("Valid input");/*TEMP*/
            /*Split(split_text);*/
        }
        else
        {
            MessageBox.Show("Please keep witin the Min-Max word count margin.", "Error - Outside Word Limit boundary");
        }

处理数组的方法和布尔值的更改:

private bool WordCount_EH(bool WordCount_Bool)
    {
        string[] TEMPWordCount_Array = input_box.Text.Split(' ');
        int j = 0;
        int wordcount = 0;
        for (int i = 100; i <=0; i--)
        { 
            if (string.IsNullOrEmpty(TEMPWordCount_Array[j]))
            {
                //do nothing
            }
            else
            {
                wordcount++;
            }
            j++;
        }

        if (wordcount >= 1)
        {
            WordCount_Bool = true;
        }
        if (wordcount < 1)
        {
            WordCount_Bool = false;
        }
        return WordCount_Bool;
    }

提前谢谢大家。

  • 旁注:我意识到for循环会抛出异常,或者至少不是最佳目的​​,所以任何建议都会受到高度赞赏。

  • 额外注意事项:对不起我应该说我没有使用长度的原因是我应该尽可能地使用自己的代码而不是使用内置函数。

4 个答案:

答案 0 :(得分:1)

简短的回答是,您应该像其他人所说的那样从WordCount_EH方法返回true或false值

但只是为了澄清为什么它不起作用。默认情况下,C#按值传递参数。使用诸如布尔值之类的值,true或false的实际值存储在变量中。因此,当您将布尔值传递给方法时,您所做的就是将此bool值放入我的新变量(方法参数)中。当您对该新变量进行更改时,它只会更改该变量。它与从中复制的变量无关。这就是为什么你没有看到原始bool变量的变化。您可能已将变量命名为相同但它们实际上是两个不同的变量。

Jon Skeet在这里http://jonskeet.uk/csharp/parameters.html

非常好地解释了这一点

答案 1 :(得分:0)

在这里你应该解决它:

if(input_box.Text.Split(' ').Length>50)
     return false;
else
     return true;

答案 2 :(得分:0)

如果要在WordCount_Bool中更改ref,则需要WordCount_EH private bool WordCount_EH(ref bool WordCount_Bool) { ... } bool WordCount_Bool = false; WordCount_EH(ref WordCount_Bool); 传递:

bool WordCount_Bool = false;
WordCount_Bool = WordCount_EH(WordCount_Bool);

虽然在这种情况下你也可以使用返回值:

{{1}}

答案 3 :(得分:0)

如果您想通过引用传递参数,则需要按照@Lee建议进行操作。

对于您的逻辑实现,您可以使用以下代码来避免数组索引。

 // It would return true if you word count is greater than 0 and less or equal to 50
 private bool WordCount_EH()
 {
      var splittedWords = input_box.Text.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).ToList();
      return (splittedWords.Count > 0 && splittedWords.Count <= 50);
 }