我是C#的新手。
当前不完整的代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace classObjectMethodBasic
{
public class Program
{
static void Main()
{
Console.WriteLine("Input a number for first number to do a math on: ");
int number1 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Input a number for second number to do a math on or you need not enter one: ");
int number2 = Convert.ToInt32(Console.ReadLine());
int result1 = new int();
result1 = Math.math(number1, number2);
Console.WriteLine("Math result: " + result1);
Console.ReadLine();
}
}
public class Math
{
public static int math(int number1, int number2 = 3)
{
int result1 = number1 + number2;
return result1;
}
}
}
需要使第二个参数(number2)为可选。 在当前代码中,如果我运行它但未输入int number2的值(意味着仅按回车键),则程序会退出,但会出现异常。 异常错误:
System.FormatException: 'Input string was not in a correct format.'
我如何使程序将第二个参数作为可选参数使用?
谢谢, 杰瑞
答案 0 :(得分:3)
更改代码以验证收到的输入会更好。在您的情况下,您可能没有输入第二个值的值,请参见下面的更正
static void Main()
{
Console.WriteLine("Input a number for first number to do a math on: ");
int number1 = 0;
string input1 = Console.ReadLine();
if (!Int32.TryParse(input1, out number1))
{
Console.WriteLine("Number 1 was entered incorrectly");
Console.ReadLine();
return;
}
Console.WriteLine("Input a number for second number to do a math on or you need not enter one: ");
int number2 = 0;
string input2 = Console.ReadLine();
if (input2.Equals(string.Empty))
{
Console.WriteLine("Math result: " + Math.math(number1));
}
else
{
if (!Int32.TryParse(input2, out number2))
{
Console.WriteLine("Number 2 was entered incorrectly");
Console.ReadLine();
return;
}
else
{
Console.WriteLine("Math result: " + Math.math(number1, number2));
}
}
Console.ReadLine();
}
答案 1 :(得分:0)
您已经声明第二个参数为可选。该错误是由于以下代码行引起的:
int number2 = Convert.ToInt32(Console.ReadLine());
您可以修改代码以在调用Math.math()
函数之前检查两个参数,或者像这样传递两个参数:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace classObjectMethodBasic
{
public class Program
{
static void Main()
{
Console.WriteLine("Input a number for first number to do a math on: ");
string input1 = Console.ReadLine();
int number1 = 0;
int.TryParse(input1, out number1);
Console.WriteLine("Input a number for second number to do a math on or you need not enter one: ");
string input2 = Console.ReadLine();
int number2 = 0;
int.TryParse(input2, out number2);
int result1 = new int();
result1 = Math.math(number1, number2);
Console.WriteLine("Math result: " + result1);
Console.ReadLine();
}
}
public class Math
{
public static int math(int number1, int number2 = 3)
{
int result1 = number1 + number2;
return result1;
}
}
}