我的while循环逻辑有什么问题?
我希望阻止用户继续进入应用程序,除非他们提供正确的输入。
目前,它只会在崩溃之前接受一个错误的输入并产生此异常:
System.Exception的: at disabler.Program.readInput(String Input) at disabler.Program.detectInput(String Input) at disabler.Program.Main(String [] 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
答案 0 :(得分:3)
您获得的异常是您抛出readInput
从readInput(result);
detectInput
根据评论更新:
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;
}