2012-02-19 66 views
1

我的搜索已空白,或者我只是不理解我發現的結果。我試圖提示用戶輸入一個布爾值,但我希望答案是yes或no。讓我知道如果你需要看到更多的代碼,但我有這個提示。C#提示布爾值

public static bool getBoolInputValue(string inputType) 
    { 
     bool valid = false; 
     bool value = true; 
     string inputString = string.Empty; 
     do 
     { 
      inputString = GetInput(inputType); 
      if (!(String.IsNullOrEmpty(inputString))) 
      { 
       valid = bool.TryParse(inputString, out value); 
      } 
      if (!valid) 
       Console.WriteLine("Invalid " + inputType + " try again!"); 
     } while (!valid); 

     return value; 
    } 

這是我的布爾值的參數。也許這需要更具體一些?

public bool Nitrus 
    { 
     set { nitrus = value; } 
     get { return nitrus; } 
    } 

謝謝你的幫助。我對編程相當陌生,但無法弄清楚。它確實成功地提示了,但是我把什麼答案放入框中並不重要,它告訴我這是不正確的格式。

+1

跳過'IsNullOrEmpty'測試,'bool.TryParse'是足夠聰明,如果返回false你傳遞一個空字符串 – 2012-02-19 23:03:53

+1

我不明白爲什麼有人會投下這個問題(我已經投了贊成票),我們都必須從某個地方開始,包括髮展自己的技能找到我們問題的答案,無論是MSDN還是其他地方。 – 2012-02-19 23:16:02

回答

2

如果我理解正確的話,你希望用戶輸入‘是’,那將意味着你有一個真正的價值。如果這是正確的,跳過所有string.IsNullOrEmptybool.TryParse的東西,做一些更是這樣。

//make it ToLower so that it will still match if the user inputs "yEs" 
inputString = GetInput(inputType); 
if (inputString.ToLower() == "yes") 
{ 
    value = true; 
} 
else 
{ 
    value = false; 
} 

//note that the if/else code is the same as directly applying 
// the value from the comparison itself: 
// value = inputString.ToLower() == "yes"; 

// this allows the user to type in "yes" or "y": 
// value = inputString.ToLower() == "yes" || inputString.ToLower() == "y"; 
+0

微軟關於使用.NET字符串的指導方針要求使用ToUpper而不是ToLower,儘管如果這是所需的行爲,指定不區分大小寫的比較可能更好。 – phoog 2012-02-20 00:33:10

+0

謝謝,這個作品。但是我的程序不斷提示我提出這個問題。由於某種原因,它顯然不喜歡答案。到下一個問題! – willisj318 2012-02-20 01:15:30

0

你的程序只接受'true'或'false'作爲有效的布爾值。如果你想'是'或'不是',那麼你需要做一個字符串比較。

valid = string.Compare(inputString, "yes", true) == 0 || string.Compare(inputString, "no", true) == 0; 

... 
value = string.Compare(inputString, "yes", true) == 0; 
+0

'? true:false'總是多餘的。 – 2012-02-19 23:16:23

+0

更新了答案,現在已經很晚了:P – devdigital 2012-02-19 23:18:04

+0

不用擔心,我也很累,只是整晚玩了16個小時的Axis and Allies遊戲:) – 2012-02-19 23:21:17

0

Boolean.TryParse只承認 「真」 與 「假」。對於「是」和「No`或‘開’和‘關’,你需要編寫自己的功能。

0
public static bool getBoolInputValue() 
{ 
    bool value; 
    bool valid; 
    do 
    { 
     Console.WriteLine("Enter yes or no: "); 
     var inputString = Console.ReadLine(); 
     if (String.IsNullOrEmpty(inputString)) 
     { 
      continue; 
     } 
     if (string.Equals(inputString, "yes") 
     { 
      value = true; 
      valid = true; 
     } 
     else if (string.Equals(inputString, "no") 
     { 
      value = false; 
      valid = true; 
     } 

    } while (!valid); 

    return value; 
} 
+0

很確定這不會編譯,因爲'valid'是未初始化的。即,如果輸入字符串是「jimmy crack corn」開始。 – 2012-02-19 23:19:58

+0

是的,我試過這個,有效的拋出一個錯誤。 – willisj318 2012-02-20 02:02:12