2017-10-19 57 views
0

对于我的项目的一部分,我希望强制执行用户输入只能在最小/最大字边界内的规则。最少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循环将抛出一个异常,或者至少不是最适合其目的,因此任何意见将非常感激。

  • 额外附注:对不起,我应该说,我没有使用长度的原因是,只要有可能,我应该做我自己的代码,而不是使用内置函数。

+2

注:当你的问题是标签的'视觉studio'家庭,才应使用*约*的Visual Studio。 “如果您有关于Visual Studio特性和功能的特定问题,请使用此标记,而不仅仅是关于您的代码的问题。” – Amy

+0

如果要在“WordCount_EH”中更改它,则需要通过'ref'传递'WordCount_Bool'这种情况下,你可能只是使用返回值。 – Lee

+0

我可能会错过一些东西,但为什么不使用TEMPWordCount_Array的长度 – Dale

回答

1

简短的回答是你应该从你的WordCount_EH方法返回一个true或false值像其他人所说

但为了清理为什么它不工作。 C#默认通过值传递参数。对于布尔型等值类型,真或假的实际值存储在变量中。所以当你将你的布尔值传递给你的方法时,你所要做的只是将这个布尔值放入我的新变量(方法参数)中。当您对该新变量进行更改时,它只会更改该变量。它与它从中复制的变量没有关系。这就是为什么你在原始布尔变量中看不到变化的原因。您可能已经命名了相同的变量,但它们实际上是两个不同的变量。

乔恩斯基特解释它飞驰在这里http://jonskeet.uk/csharp/parameters.html

+1

谢谢你的描述性答案。问题仍然没有解决,但是,我怀疑它更可能是由于循环。在阅读你的答案之后,我进一步阅读并进行实验,现在了解通过价值传递和通过参考传递之间的差异。 :) – Jurdun

0

在这里你去这应该解决它:

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

您需要通过ref通过WordCount_Bool如果你想改变它在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); 
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); 
}