2015-04-17 55 views
0

什麼是錯我的do while循環的邏輯?做而當條件爲真不循環迴路

我想阻止用戶進一步繼續到應用程序,除非他們提供正確的輸入。

目前,它只能接受一個輸入錯誤崩潰併產生這個異常之前:

的System.Exception: 在disabler.Program.readInput(字符串輸入) 在disabler.Program.detectInput(串輸入) 在disabler.Program.Main(字串[] args)

這是我的代碼:

private static string detectInput(string Input) 
    { 
     string result= Input; 
     do 
     { 
      //pass input to readInput method 
      if ((result == "exit") || (result == "query") || (result == "disable")) 
      { 
       readInput(result); 
      } 
      else 
      { 
       Console.WriteLine("invalid input detected. Please try again."); 
       result= Console.ReadLine(); 
       readInput(result); 
      } 
     } 
     while (!((result == "exit") || (result == "query") || (result == "disable"))); 
     return result; 
    } 

下面是readInput方法的代碼:

//Read user input 
    private static string readInput(string Input) 
    { 
     int successfullyDisabled = 0; 
     string input = string.Empty; 
     switch (Input) 
     { 
      case "disable": 
          int disableCounter = 0; 
       invalidAccount.ForEach(delegate(String samAccountName) 
       { 
        disableCounter++; 
        Console.Write(disableCounter); 
        //disable inactive accounts 
        if (DisableADUser(samAccountName)) 
        { 
         successfullyDisabled++; 
        } 
       }); 

       invalidAccount.Clear();      
       validAccount.Clear(); 
       Console.WriteLine("Press [ENTER] to continue or [ESC] to exit.\n"); 
       break; 
      case "query":     
          Console.WriteLine("No.\t | Dep | User Account\t  | Status");        
          int countRow = 0; 
       validAccount.ForEach(delegate(String samAccountName) 
       { 
        countRow++; 
        Console.Write(countRow); 
        //find status of active accounts 
        findUserStatus(samAccountName); 
       }); 
       validAccount.Clear(); 
       invalidAccount.Clear(); 
       Console.WriteLine("Press [ENTER] to continue or [ESC] to exit.\n"); 
       break; 
      case "exit": 
       //leave console 
       Environment.Exit(2); 
       invalidAccount.Clear(); 
       validAccount.Clear(); 
       break; 
      default: 
       throw new Exception("Invalid command entered. Please enter command again."); 
     } 
     return input; 
    }//end of ReadInput 
+1

什麼是異常消息? readInput有什麼作用? –

+2

異常顯示它正在被'readInput'方法拋出。爲了幫助任何可能有興趣回答這個問題的人,你會如此友好,以便包含它的代碼。 – Alex

+4

你是否真的想檢查'exit'兩次? – paxdiablo

回答

3

你所得到的例外是,你扔在readInput

switch語句從detectInput

的else刪除readInput(result);異常基於註釋更新:

private static string detectInput(string Input) 
{ 
    string result= Input; 
    while (!((result == "exit") || (result == "query") || (result == "disable"))); 
    {    
      Console.WriteLine("invalid input detected. Please try again."); 
      result= Console.ReadLine(); 
     } 
    } 

    result = readInput(result); 

    return result; 
} 
+0

請你編輯你的答案並顯示更正後的代碼,我會很樂意給予好評它 – Carsten

+0

您可能要擴大這個回答有點,因爲它是正確的,但它不是從你如何寫清楚,並且需要更多一點的闡述。 – Alex