我正在努力让它在输入数字时不会崩溃,到目前为止就是这样。然后我希望它重新请求输入,直到插入正确的字符类型。
int firstNum;
int Operation = 0;
switch(Operation)
{
case 1:
bool firstNumBool = int.TryParse(Console.ReadLine(), out firstNum);
break;
}
分解您的解决方案提取用于输入整数的方法:
private static int ReadInteger(string title) {
// Keep on asking until correct input is provided
while (true) {
if (!string.IsNullOrWhiteSpace(title))
Console.WriteLine(title);
if (int.TryParse(Console.ReadLine(), out int result))
return result;
Console.WriteLine("Sorry, not a valid integer value; please, try again.");
}
}
然后使用它:
int firstNum;
...
switch(Operation)
{
case 1:
firstNum = ReadInteger("First number");
break;
...