【发布时间】:2021-12-12 18:25:37
【问题描述】:
我想学习如何在我的代码中实现 int.tryparse 命令,以防止程序因输入无效而崩溃。这是我到目前为止所写的:
using System;
namespace barn_
{
class Program
{
static void Main(string[] args)
{
int age;
string a;
do
{
Console.WriteLine("How old is the person?");
age = Convert.ToInt32(Console.ReadLine());
a = Convert.ToString(Console.ReadLine());
bool v = int.TryParse(a, out age);
while(a == true)
{
Console.WriteLine("");
Console.WriteLine("");
}
if (age >= 2 && age <= 5)
{
Console.ForegroundColor = ConsoleColor.Blue;
Console.WriteLine("The person has blue clothes.");
}
else if (age >= 6 && age <= 9 || age >= 10 && age <= 15)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("The person has red clothes.");
}
else if (age < 2)
{
Console.WriteLine("The person is too young.");
Console.WriteLine();
}
else if (age > 15)
{
Console.WriteLine("The person is too old.");
Console.WriteLine();
}
} while (age < 2 || age > 15);
}
}
}
【问题讨论】:
-
你确定它在 bool v = int.TryParse(a, out age); 上崩溃了吗?声明而不是年龄 = Convert.ToInt32(Console.ReadLine());?是否有异常写入控制台或系统的事件查看器,您可以发布?
-
您遇到的另一个问题是 while 循环
while(a == true)... 这永远不会退出。使用 try / catch 确保输入有效。 -
a = Convert.ToString(Console.ReadLine());bool v = int.TryParse(a, out age);为什么需要这两行? -
我对@987654325@ 的用途感到非常困惑。如果该变量实际上有一个有意义的名称可能会有所帮助,但即便如此,我还是不明白这一点。与
v类似。您的变量应具有描述性名称。 -
我在代码中没有异常。您在帖子中看到的是代码。我需要年龄 = Convert.ToInt32(Console.ReadLine());语句,以便用户实际上可以输入一个整数。它不会在 v = int.TryParse(a, out age); 上崩溃据我所知的声明。只有当用户用文本或十进制数字对问题 Console.WriteLine("How old is the person?"); 做出响应时,它才会崩溃;在控制台中。 @spyder1329
标签: c# string input error-handling integer