我知道如何检查用户输入是否无效,但我不知道如何再次询问。
在我的代码中,如果用户输入是字符串,则显示“无效输入”并退出控制台
但是我要它再次询问“请输入您的第一个数字:”,直到答案是数字!
我尝试了while循环,但失败了。
有人可以告诉我怎么做吗?
int Summation = 0;
Console.Write("\n\t\t\tPlease enter your first number: ");
string firstNumberInput = Console.ReadLine();
if (!int.TryParse(firstNumberInput, out int FirstNumber))
{
Console.WriteLine("\n\t\t\tInvalid input!");
Console.Beep();
Environment.Exit(0);
}
Console.Write("\n\t\t\tPlase enter your second number: ");
string secondNumberInput = Console.ReadLine();
if (!int.TryParse(secondNumberInput, out int SecondNumber))
{
Console.WriteLine("\n\t\t\tInvalid input!");
Console.Beep();
Environment.Exit(0);
}
Console.Write("\n\t\t\tNow chose your operator(+, -, *, /): ");
string Operator = Console.ReadLine();
switch (Operator)
{
case "+":
Summation = FirstNumber + SecondNumber;
break;
case "-":
Summation = FirstNumber - SecondNumber;
break;
case "*":
Summation = FirstNumber * SecondNumber;
break;
case "/":
Summation = FirstNumber / SecondNumber;
break;
default:
Console.WriteLine("\n\t\t\tThe operator is not valid!");
Console.Beep();
Environment.Exit(0);
break;
}
Console.WriteLine("\n\t\t\tYour answer is {0}", Summation);
答案 0 :(得分:1)
每当您要重复一个动作时,您所说的就是一个“循环”。对于循环,您只需要重复一段代码以及在循环中保留的条件即可。例如,考虑这样的事情:
// declare your variables
var firstNumber = 0;
var validInput = false;
// loop until you have valid input
while (!validInput)
{
// get the input
Console.Write("\n\t\t\tPlease enter your first number: ");
var firstNumberInput = Console.ReadLine();
// validate it
validInput = int.TryParse(firstNumberInput, out firstNumber);
// if it was invalid, notify the user
if (!validInput)
{
Console.WriteLine("\n\t\t\tInvalid input!");
Console.Beep();
}
}
这将连续循环直到输入有效为止。