所以我最近开始了我的第一个C#编码课程。我目前正在尝试编写一个打印出Yay的短程序!我指出的次数。现在为了防止任何格式异常,我试图添加一个try并捕获它。但是,由于某些原因,这不起作用,我似乎无法弄清楚原因。代码如下:
Console.Write("Enter the number of times to print \"Yay!\": ");
string entry = Console.ReadLine();
var number = int.Parse (entry);
bool print = true;
while(print)
{
try
{
if(number <= 0)
{
print = false;
}
else
{
Console.WriteLine("Yay!");
number -= 1;
}
}
catch(FormatException)
{
Console.WriteLine("You must enter a whole number.");
}
}
据我所知,我拥有完成这项工作所需的一切。任何人都可以看到我在哪里出错了吗?
非常感谢您的阅读!
答案 0 :(得分:2)
这是
var number = int.Parse (entry);
应抛出异常,并且因为超出 try {}
范围,
异常尚未被发现。将片段移动到范围中:
Console.Write("Enter the number of times to print \"Yay!\": ");
string entry = Console.ReadLine();
bool print = true;
try {
// int.Parse is within the try {} scope now
var number = int.Parse (entry);
while(print) {
...
}
}
catch(FormatException) {
Console.WriteLine("You must enter a whole number.");
}
或将int.Parse
转换为int.TryParse
并放弃try {...} catch {...}
(更好的解决方案)
Console.Write("Enter the number of times to print \"Yay!\": ");
int number;
if (!int.TryParse(Console.ReadLine(), out number)) {
Console.WriteLine("You must enter a whole number.");
return;
}
bool print = true;
// There's no need in try {} catch {} now
while(print) {
...
}
答案 1 :(得分:0)
您需要将int.Parse
放在try-catch块中。
以下是您的代码的修订版。
static void Main(string[] args)
{
bool print = true;
while (print)
{
Console.Write("Enter the number of times to print \"Yay!\": ");
string entry = Console.ReadLine();
try
{
var number = int.Parse(entry);
for (int i = 0; i < number; i++)
{
Console.WriteLine("Yay!");
}
}
catch (FormatException)
{
Console.WriteLine("You must enter a whole number.");
}
}
}