2012-01-01 256 views
0

我不知道它是否只是我很厚,但我有一些驗證代碼來檢查是或否的答案。c#!=操作員不能正常工作

我似乎無法得到它的工作我已經在我的程序中的其他地方使用的代碼,它的工作原理,但我不能發現錯誤,如果有的話。無論如何,代碼貫穿整個輸入字符。

string correctDestenation = Console.ReadLine().ToLower(); 
while (correctDestenation != "y" || correctDestenation != "n") 
{ 
    Console.WriteLine(
     "Oops! You must enter a 'y' for yes and a 'n' for no"); 
    correctDestenation = Console.ReadLine().ToLower(); 
} 
+2

它不應該是||您必須使用&& – Baatar 2012-01-01 14:03:13

+5

在懷疑操作員之前,懷疑自己的邏輯和代碼。 – Oded 2012-01-01 14:04:46

+3

我認爲這是一個相當大膽的主張不平等運算符'!='不起作用。 – 2012-01-01 14:04:54

回答

8

您的邏輯錯誤。您想使用& &而不是||。

while (correctDestenation != "y" && correctDestenation != "n") 

,或者您可以使用De Morgan's Law,看看它的其他方式,這相當於:

while (!(correctDestenation == "y" || correctDestenation == "n")) 
+0

我知道這是簡單的感謝 – bobthemac 2012-01-01 14:45:51

2

這條件總是被滿足,作爲一個字符將不等於「Y」或等於'n'。使用& &而不是||。

1

你怎麼樣使用AND運算符

while (correctDestenation != "y" && correctDestenation != "n") 
    { 
      Console.WriteLine("Oops! You must enter a 'y' for yes and a 'n' for no"); 
      correctDestenation = Console.ReadLine().ToLower(); 
    }