2015-09-19 33 views
3

我想問如果輸入是一個合法的數值變量。我試過這種方法(它顯示錯誤的輸出,如圖所示),用==和else(其中說,否則是錯誤的),不知道爲什麼它不工作。任何建議或其他方式試圖做到這一點將不勝感激。如果,不等於和或幫助(不知道哪個)

static void start() 
{ 
    // start of broken code 

    Console.WriteLine("Please select a variable type"); 
    string selection = Console.ReadLine(); 
    if ((selection != "short") || (selection != "ushort") || (selection != "int") || (selection != "uint") || (selection != "byte") || (selection != "long") || (selection != "ulong")); 
    { 
     Console.WriteLine("That is not a correct form of variable"); 
     Console.WriteLine("Let's try this again"); 
     start(); 
    } 

    // end of broken code 

    Console.WriteLine("You selected ", selection); 
    Console.WriteLine("Is this correct? (Y/N)"); 
    string sure = Console.ReadLine(); 
    if (sure == "Y") 
    { 
     Console.WriteLine("Let's begin!"); 
     calculator(); 
    } 
    else 
    { 
     Console.WriteLine("Let's try this again"); 
     start(); 
    } 
} 

輸出: 請選擇一個變量類型 INT //我已經進入 這是不變量 的正確形式,讓我們試着這又 請選擇一個變量類型

回答

3

使用 '& &' 而不是 '||'如果任何這些條件返回true,則評估返回true,從而確保它失敗,因爲它只能是一個選項。

6

有2這條線的問題:

if ((selection != "short") || (selection != "ushort") || (selection != "int") || (selection != "uint") || (selection != "byte") || (selection != "long") || (selection != "ulong")); 

||或& &

這條線,用簡單的英語,是在說:如果用戶的選擇不是「短」,它不是「USHORT」等不管是什麼樣的選擇就不能這兩個 - 所以你總是會得到消息「這不是一個正確的變量形式」。

相反,你要來檢查代碼,如果用戶的選擇不是「短」,它不是「USHORT」等因此,如果選擇相匹配的允許可能性的任何一個,你會繼續到確認步驟。

;在if條件之後

在線末端有一個;,它不應該在那裏。它具有爲條件主體放置一個空白塊的作用,並且不管條件結果如何,應始終處於條件主體中的代碼將始終執行。所以,你的代碼

if ((selection != "short") && (selection != "ushort") ...); 
{ 
    Console.WriteLine("That is not a correct form of variable"); 
} 

相當於

if ((selection != "short") && (selection != "ushort") ...) 
{} 

Console.WriteLine("That is not a correct form of variable"); 

刪除分號,它會像預期的那樣。

if ((selection != "short") && (selection != "ushort") ...) 
{ 
    Console.WriteLine("That is not a correct form of variable"); 
} 
+1

我按照你的建議完成了,但是控制檯仍然返回'int'不是一個有效的變量。 Console.WriteLine(「請選擇變量類型」); string selection = Console.ReadLine(); (選擇!=「短」)&&(選擇!=「ushort」)&&(選擇!=「int」)&&(選擇!=「uint」)&&(選擇!=「字節」)&&(選擇)( !=「long」)&&(selection!=「ulong」)); Console.WriteLine(「這不是一個正確的變量形式」); Console.WriteLine(「讓我們再試一次」); start(); } –

+0

發現第二個問題與該行,答案更新 – sheilak

+1

是的,工作,謝謝你 –