例如,假设我有和int调用输入。然后我得到它的输入。像这样:
input = Console.ReadLine();
但是当用户收到提示时,输入是一个字符串,然后它会收到错误并导致程序崩溃。如何检查输入的字符串是否输入?
是否有类似if (input.equals(string))
之类的选项?
string numberOne;
string numberTwo;
double answer;
string operand;
Console.WriteLine("Enter the first number");
numberOne = Console.ReadLine();
if (double.TryParse(numberOne, out double value))
{
Convert.ToInt32(numberOne);
}
else
{
Console.WriteLine("Non integer entered. Please enter a valid number.");
}
Console.WriteLine("Enter the operator");
operand = Console.ReadLine();
Console.WriteLine("Enter the second number");
numberTwo = Console.ReadLine();
if (double.TryParse(numberTwo, out double value2))
{
Convert.ToInt32(numberTwo);
}
else
{
Console.WriteLine("Non integer entered. Please enter a valid number.");
}
switch(operand)
{
case "+":
answer = numberOne + numberTwo;
Console.WriteLine("The answer is " + answer);
break;
case "-":
answer = numberOne - numberTwo;
Console.WriteLine("The answer is " + answer);
break;
case "*":
answer = numberOne * numberTwo;
Console.WriteLine("The answer is " + answer);
break;
case "/":
answer = numberOne / numberTwo;
Console.WriteLine("The answer is " + answer);
break;
default:
Console.WriteLine("Please enter a valid operator such as +, -, *, or /");
break;
}
答案 0 :(得分:2)
Console.Readline()总是返回一个字符串,但是你可以这样做来检查一个整数是否被输入并继续询问输入的正确类型,直到用户交付它为止。
(?:FTE )(YUY|GWU)
答案 1 :(得分:1)
Console.ReadLine
始终返回string
。根据从控制台读取的内容,它不会返回不同类型的内容。您的工作是确定输入的值是否符合您的要求(在这种情况下,它应该是可以解析为int的东西)。
您可以使用int.TryParse
尝试将字符串解析为int
,而不会在解析失败时抛出异常。
string input = Console.ReadLine();
if(int.TryParse(input, out int value))
{
// value contains an int parsed out of input
}
else
{
// parsing fails, you can do something about that, e.g. ask user for different input
}