【发布时间】:2012-07-10 06:00:33
【问题描述】:
我的手腕被打了一巴掌,因为在一个作业中,当输入错误发生时,我有一个方法调用本身。我不知道如何或使用什么来代替我编写的代码。我需要帮助才能找到正确的方法。
我喜欢编码,所以我只需要以正确的方式推动! :)
我写的代码是这样的。
private void SumTheNumbers()
{
Console.Write("Please give the value no "+ index + " :");
if (false == int.TryParse(Console.ReadLine(), out num))
{
//Errormessage if the user did not input an integer.
Console.WriteLine("Your input is not valid, please try again.");
Console.WriteLine();
sum = 0;
SumTheNumbers();
}
else
{
//Calculate the numbers given by user
sum += num;
}
}
【问题讨论】:
-
我假设他们期待一个显式循环?
-
您在寻找循环吗?参见例如
while关键字。 -
这段代码的一个更糟糕的风格问题是使用了全局变量。
-
@BenVoigt - 他们很可能从私有方法访问类成员。我看不出这有什么问题。理想情况下,虽然我尽量保持我的功能尽可能纯,但你不能总是这样做。
-
@ChaosPandion:
num没有充分的理由成为班级成员,并且有几个理由让它成为本地成员。这是一种糟糕的风格。