所以我试图让我的控制台应用程序在Visual Studio上接受来自用户的空白答案,然而,在两个空白答案后,我得到一个错误。我正在使用try/catch而不是if/else,似乎我的可选参数只是没有按我认为它应该的方式工作。任何帮助将非常感激!
My Program.cs code:
static void Main(string[] args)
{
try
{
Operator operatorObject = new Operator();
Console.WriteLine("Pick a number:");
int data = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Pick another number--optional");
int input = Convert.ToInt32(Console.ReadLine());
int result = operatorObject.operate(data, input);
Console.WriteLine(result);
Console.ReadLine();
}
catch
{
Operator operatorObject = new Operator();
int data = Convert.ToInt32(Console.ReadLine());
int result = operatorObject.operate(data);
Console.WriteLine(result);
Console.ReadLine();
}
}
}
my class code:
public class Operator
{
public int operate(int data, int input = 0)
{
return data + input;
}
}
可以这样使用TryParse:
static void Main(string[] args)
{
try
{
Operator operatorObject = new Operator();
Console.WriteLine("Pick a number:");
int data = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Pick another number--optional");
int input;
bool inputResult = Int32.TryParse(Console.ReadLine(), out input);
int result = operatorObject.operate(data, input);
Console.WriteLine(result);
Console.ReadLine();
}
catch
{
Operator operatorObject = new Operator();
int data;
bool dataResult = Int32.TryParse(Console.ReadLine(), out data);
int result = operatorObject.operate(data);
Console.WriteLine(result);
Console.ReadLine();
}
}