我想这样做是因为我想阻止会导致程序崩溃的输入。我尝试这样做,但我得到错误使用未分配的参数total和out参数totalstring和total必须在控制离开当前方法之前分配。
private static void Start(out String totalString, out int total)
{
Console.WriteLine("How Many ? (2-4)");
Console.WriteLine("");
try
{ totalString = Console.ReadLine();
total = int.Parse(totalString);
}
catch
{
Console.WriteLine("");
}
bool flag = false;
if ((total <= 1) || (total > 4)) //loop to reject invaid input
while (flag == false)
{
if ((total <= 1) || (total > 4))
{
Console.WriteLine("Invalid input. How many?");
totalString = Console.ReadLine();
total = int.Parse(totalString);
Console.Clear();
}
else if ((total >= 2) || (total <= 4))
{
flag = true;
}
}
Console.Clear();
Console.WriteLine("Player Numbers :" + total);
Console.WriteLine();
players = new Player[total];
}
}
}
很抱歉:)
答案 0 :(得分:2)
我宁愿使用TryParse
代替Parse
:
简洁:
int total;
do {
Console.WriteLine("How Many ? (2-4)");
}
while (!(int.TryParse(Console.ReadLine(), out total) && (total >= 2) && (total <= 4)))
健谈:
int total;
Console.WriteLine("How Many ? (2-4)");
while (true) {
if (!int.TryParse(Console.ReadLine(), out total)) {
Console.WriteLine("Invalid input. How many?");
else if ((total < 2) || (total > 4)) {
Console.WriteLine("Invalid range. How many?");
else
break;
}
答案 1 :(得分:0)
如果您的方法具有out
个参数,则必须始终为它们分配值,无论代码采用何种路径。这是该错误消息试图告诉您的内容。
当你有
时 try
{ totalString = Console.ReadLine();
total = int.Parse(totalString);
和&#34; Console.ReadLine()&#34;抛出错误,然后未分配totalString
和total
。同样,当ReadLine成功但int.Parse失败时,则不会分配total
。
简单解决方案:在方法开头指定默认值:
totalString = null;
total = 0;
当一切顺利时,这些都会被覆盖。
答案 2 :(得分:0)
您可以在此处进行两项改进:
1摆脱out
参数并返回播放器数组,而不是使用void方法。
2使用do while
循环代替当前代码:
private static IEnumerable<Player> Start()
{
do
{
Console.WriteLine("How Many ? (2-4)");
Console.WriteLine("");
try
{
var totalString = Console.ReadLine();
var total = int.Parse(totalString);
if (total >= 1 && total <= 4)
{
Console.WriteLine("Number of players :" + total);
return new Player[total];
}
}
catch
{
Console.WriteLine("Invalid input.");
}
} while (true)
}
答案 3 :(得分:0)
您收到此错误是因为total
从未分配给int.Parse()
引发异常,但您在catch
阻止之后仍在使用它。
要避免这种情况,请检查total
是否为空。
Dmitry Bychenko为您提供了一个非常简洁的替代方案,所以我要在您的代码中指出一些小问题。
Console.ReadLine()
已经是一个字符串,这可行:
total = int.Parse(Console.ReadLine);
您检查total
两次,一次在外if
块中,再次在while
循环中。你不必这样做。
一旦你在循环中进行第二次解析尝试并输入无效的东西,就会抛出异常,但你不会处理它。
为了您自己,请格式化您的代码。
尽量避免不必要的例外。如果抛出异常,应用程序会冻结几秒钟,既不好看也不好用。例如,如果解析尝试失败,TryParse
会返回false
。