我正在从Python切换到C#,我遇到了这个ReadLine()功能的问题.如果我想要求用户输入Python,我就是这样做的:
x = int(input("Type any number: "))
Run Code Online (Sandbox Code Playgroud)
在C#中,这变为:
int x = Int32.Parse (Console.ReadLine());
Run Code Online (Sandbox Code Playgroud)
但是如果我输入这个,我会收到一个错误:
int x = Int32.Parse (Console.ReadLine("Type any number: "));
Run Code Online (Sandbox Code Playgroud)
如何让用户在C#中输入内容?
你应该改变这个:
int x = Int32.Parse (Console.ReadLine("Type any number: "));
Run Code Online (Sandbox Code Playgroud)
对此:
Console.WriteLine("Type any number: "); // or Console.Write("Type any number: "); to enter number in the same line
int x = Int32.Parse(Console.ReadLine());
Run Code Online (Sandbox Code Playgroud)
但是如果你输入一些字母(或另一个无法解析的符号int),你会得到一个Exception.要检查输入的值是否正确:
(更好的选择):
Console.WriteLine("Type any number: ");
int x;
if (int.TryParse(Console.ReadLine(), out x))
{
//correct input
}
else
{
//wrong input
}
Run Code Online (Sandbox Code Playgroud)