2014-01-07 25 views
-4

所以,我試圖做一個循環,如果有人輸入一個字符它會執行。如果它是錯的,它將不會顯示一個選項。如果我在Array()方法之後的末尾添加Else {Console.WriteLine("Not an option"),它也不起作用。 所以,我不完全確定我在做什麼。這是否甚至需要一個循環?正如我想象的那樣工作?任何建議都會很棒。循環char不工作

class Program 
{ 
    static void Main(string[] args) 
    { 

     string _a = ""; 
     constructor dick = new constructor(); 
     Console.WriteLine("Enter C for constructor, M for method, A for an array..."); 
     Console.WriteLine("Please reference source code to have full details and understanding..."); 
     while (_a.ToUpper() == "C" || "M" || "A") 
     { 
      _a = Console.ReadLine(); 
      if (_a.ToUpper() == "C") 
      { 
       Console.WriteLine(dick.a); 
      } 
      if (_a.ToUpper() == "M") 
      { 
       Shit(); 
      } 
      if (_a.ToUpper() == "A") 
      { 
       Array(); 
      } 
     } 
    } 

    public class constructor 
    { 
     public string a = "This is a constructor!"; 
    } 
    static public void Shit() 
    { 
     string b = "This is a method!"; 
     Console.WriteLine(b); 
    } 
    static public void Array() 
    { 
     Console.WriteLine("\nHow large of an array?\n"); 
     string sSize = Console.ReadLine(); 
     int arraySize = Convert.ToInt32(sSize); 
     int[] size = new int[arraySize]; 
     Random rd = new Random(); 
     Console.WriteLine(); 
     for (int i = 0; i < arraySize; i++) 
     { 
      size[i] = rd.Next(arraySize); 

      Console.WriteLine(size[i].ToString()); 
     } 

    } 

} 
} 
+5

我建議你的名字您的對象以更合適的方式。 – Szymon

+0

你可能想用'switch'語句嘗試它,打破每種情況。事實上,即使第一個匹配,你也執行所有的'if'。 – HABO

回答

4

,而不是這樣的:

while (_a.ToUpper() == "C" || "M" || "A") 

定義布爾變量,如果要強制用戶輸入正確的字符

bool control = true; 

while (control) 
{ 
    _a = Console.ReadKey(); 
    var character = _a.KeyChar.ToString().ToUpper(); 
    switch (character) 
     { 
      case "C": 
       Console.WriteLine(dick.a); 
       control = false; 
       break; 
      case "M": 
       control = false; 
       Shit(); 
       break; 
      case "A": 
       control = false; 
       Array(); 
       break; 
      default: 
       Console.WriteLine("You entered wrong character"); 
       break; 
     } 
} 

,是的,你需要一個loop.And使用Console.ReadKey而不是Console.ReadLine如果輸入只是一個字符

+0

如果我想讓它在用戶輸入錯誤的字符時向用戶顯示響應,那麼它會是其他的嗎?例如,如果有人輸入B,讓他們知道這是不正確的。 – Zoro

+1

是的,您可以在開關中使用默認語句,請參閱我的更新 –

+0

現在完全瞭解。我真的寫得很快。因此生氣是代碼中的粗俗。有沒有辦法做到這一點除了大小寫切換語句,或者這是理想的是這樣的東西是爲什麼設計的? – Zoro