我正在寻求用户在控制台上的输入
cki = Console.ReadKey();
Console.WriteLine("");
string character = cki.KeyChar.ToString();
if (character == "1")
{
Console.WriteLine("Please wait...");
Name_Updater nu = new Name_Updater();
nu.Name_Update();
}
else if (character == "2")
{
Console.WriteLine("Please wait...");
WCM_Interaction wi = new WCM_Interaction();
wi.Interact_WCM();
}
else
{
Console.WriteLine("Invalid key! Please try again");
}
但如果用户输入无效输入,则在一次迭代后停止。但是我希望它接受来自用户的输入,直到它收到有效输入,但我对放置循环的位置感到困惑。
答案 0 :(得分:1)
cki = Console.ReadKey();
string character = cki.KeyChar.ToString();
while (true) // infinite loop
{
if (character == "1")
{
Console.WriteLine("Please wait...");
Name_Updater nu = new Name_Updater();
nu.Name_Update();
break; // break from loop if you read "1"
}
if (character == "2")
{
Console.WriteLine("Please wait...");
WCM_Interaction wi = new WCM_Interaction();
wi.Interact_WCM();
break; // break from loop if you read "2"
}
// repeat loop if invalid entery
Console.WriteLine("Invalid key! Please try again");
cki = Console.ReadKey();
character = cki.KeyChar.ToString();
}
答案 1 :(得分:1)
bool correctInput = false;
while (!correctInput)
{
correctInput = true;
string decision = Console.ReadLine();
int iDecision;
if (int.TryParse(decision, out iDecision))
switch (iDecision)
{
case 0:
// do something
break;
case 1:
// do something else
break;
default:
correctInput = false;
break;
}
else
correctInput = false;
if (!correctInput)
Console.WriteLine("Tell user their input was bad.");
}
答案 2 :(得分:0)
您可以放置一个do while
循环来进行迭代。它可以嵌入:
cki = Console.ReadKey();
Console.WriteLine("");
string character;
bool flag=true;
do
{
character = cki.KeyChar.ToString();
if (character == "1")
{
Console.WriteLine("Please wait...");
Name_Updater nu = new Name_Updater();
nu.Name_Update();
flag=false;
}
else if (character == "2")
{
Console.WriteLine("Please wait...");
WCM_Interaction wi = new WCM_Interaction();
wi.Interact_WCM();
flag=false;
}
else
{
Console.WriteLine("Invalid key! Please try again");
}
}while(flag)
答案 3 :(得分:0)
您可以这样做,它的作用是创建一个标志,然后在满足条件时将其设置为true。
bool isValid = false;
while (!isValid)
{
var cki = Console.ReadKey();
Console.WriteLine("");
string character = cki.KeyChar.ToString();
if (character == "1")
{
Console.WriteLine("Please wait...");
//Name_Updater nu = new Name_Updater();
//nu.Name_Update();
isValid = true;
}
else if (character == "2")
{
Console.WriteLine("Please wait...");
//WCM_Interaction wi = new WCM_Interaction();
//wi.Interact_WCM();
isValid = true;
}
else
{
Console.WriteLine("Invalid key! Please try again");
}
}