我已经尝试过几十次了,但是我似乎不明白为什么执行这一行?
Console.WriteLine(“请输入一个数字”);
在输入任何字符之前,我就会在屏幕上看到它。任何帮助都是非常感谢的。
int numberAsInt;
while (true) {
try {
numberAsInt = Convert.ToInt32(Console.ReadLine());
break;
}
catch {
Console.WriteLine("please enter a number.");
}
}发布于 2017-01-05 19:20:32
触发catch块的原因是,有一个异常是由以下原因引起的:
Convert.ToInt32(Console.ReadLine())ReadLine()方法将读取您已经输入的任何内容--即使没有任何内容。来自MSDN
从输入流返回下一行字符,如果没有更多行可用,则返回null。 如果标准输入设备是键盘,则ReadLine方法会阻塞,直到用户按下Enter键。
发布于 2017-01-05 19:30:46
您不应该使用try/catch检查您的输入。更好的方法:
int numberAsInt;
while (true) {
String str = Console.ReadLine();
if (int.TryParse(str, out numberAsInt)) {
break;
}
Console.WriteLine("please enter a number.");
}发布于 2017-01-05 19:37:24
不需要一个无限while循环和一个try/catch块来验证用户是否输入了一个有效的数字,您可以使用int.TryParse()代替。
int num;
string input = "";
while (!int.TryParse(input, out num))
{
Console.Write("Enter a number:");
input = Console.ReadLine();
}
Console.WriteLine("Number entered:" + num);https://stackoverflow.com/questions/41492821
复制相似问题