使用int32.TryParse处理错误
本文关键字:错误 处理 TryParse int32 使用 | 更新日期: 2023-09-27 18:20:18
我在添加错误消息和重新循环时遇到了问题,我想知道如何添加"输入错误,再试一次",然后试着写下正确的数字。它不会崩溃,到目前为止这很好,但我希望在不使用try-and-catch和循环的情况下出现错误,该循环迫使您只写正确的数字。
以下是我迄今为止所做的代码:
bool loopie = true;
int result;
int result2;
int result3;
while (loopie)
{
Console.Write("Number one: ");
Int32.TryParse(Console.ReadLine(), out result);
Console.WriteLine(" ");
Console.Write("Number two: ");
Int32.TryParse(Console.ReadLine(), out result2);
Console.WriteLine(" ");
Console.Write("Number two: ");
Int32.TryParse(Console.ReadLine(), out result3);
Console.WriteLine(" ");
int summa = result + result2 + result3;
Console.WriteLine("summan: " + summa);
}
Console.ReadKey();
int result, result2, result3;
private int GetResult(string msg)
{
int temp;
do
{
Console.Write(msg);
}
while(!Int32.TryParse(Console.ReadLine(), out temp));
return temp;
}
void Main()
{
var result = GetResult("Number one:");
var result2 = GetResult("Number two:");
var result3 = GetResult("Number three:");
Console.WriteLine("summan: " + (result + result2 + result3).ToString());
}
如果我们想变得更加"优雅"(以可读性和以后使用result
变量值的能力为代价):
void Main()
{
Console.WriteLine("summan: " + (GetResult("Number one:") +
GetResult("Number two:") +
GetResult("Number three:")).ToString());
}
TryParse返回bool,指定转换是否正确。所以使用它。
while (loopie)
{
Console.Write("Number one: ");
if (!Int32.TryParse(Console.ReadLine(), out result))
{
Console.WriteLine("Wrong input. try again.");
continue;
}
Console.WriteLine(" ");
Console.Write("Number two: ");
if (!Int32.TryParse(Console.ReadLine(), out result2))
{
Console.WriteLine("Wrong input. try again.");
continue;
}
Console.WriteLine(" ");
Console.Write("Number two: ");
if (!Int32.TryParse(Console.ReadLine(), out result3))
{
Console.WriteLine("Wrong input. try again.");
continue;
}
Console.WriteLine(" ");
int summa = result + result2 + result3;
Console.WriteLine("summan: " + summa);
}
如果你不想在失败后重置整个过程,也可以再使用一段时间。
do
{
Console.Write("Number one: ");
Console.WriteLine("Wrong input. try again.");
} while (!Int32.TryParse(Console.ReadLine(), out result)); // write this for all 3 inputs.