2017-10-19 58 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); 
}