我正在编写一个添加数字的程序。程序将来自用户的输入作为整数值并且总共给出两个数字。但我希望当用户输入除数字之外的任何字符时,会向控制台写入自定义错误。如何使用if
和else
?
我的代码:
class Program
{
static void Main(string[] args)
{
double firstnum, secondnum, total;
Console.WriteLine("FIRST NUMBER");
firstnum = Convert.ToDouble(Console.ReadLine());
if (Console.ReadLine == char)
{
Console.WriteLine("error... error wrong keyword, enter only numbers...");
}
Console.WriteLine("SECOND NUMBER");
secondnum = Convert.ToDouble(Console.ReadLine());
total = firstnum + secondnum;
Console.WriteLine("TOTAL VALUE IS =" + total);
Console.ReadLine();
答案 0 :(得分:1)
首先将字符串读入字符串变量。然后使用TryParse
将其转换为数字。如果字符串不是有效数字,它将返回false
,您可以使用它来显示错误。
var firstNumAsString = Console.ReadLine();
int firstNum;
if (!int.TryParse(firstNumAsString, out firstNum))
{
Console.WriteLine("error... error wrong keyword, enter only numbers...");
return;
}
如果您想抛出异常而不是仅显示错误,请使用int.Parse
。如果输入无效,它将抛出FormatException
或OverflowException
。