我的问题是如何重新编写此代码,以便在用户决定输入更多保龄球分数时数组将自行清除?
while (!userIsDone)// loop will continue as long as the userIsDone = false
{
Console.Write("\nWould you like to process another set of bowling scores?");// prompt user to input Y or N to quit or to
Console.WriteLine("\nPress 'Y' to process another set or 'N' to exit the program");// input new bowling scores
string userInput = Console.ReadLine();// reads the user input to check against if/else below
if (userInput == "N")// if userInput is literal N the program will exectute this block
{
userIsDone = true;//exits program by setting userIsDone to true
}
else if (userInput == "Y")//if the user inputs a literal Y this block will execute
{
Console.Clear();// clears the console
break;// jumps out of the loop and returns to the prompt to input scores
}
else
{
// left blank to end the if and return to beginning of while because userInput was not Y or N
}
}//end while
//end do while
} while (!userIsDone);// continues to loop until userIsDone is true
}
}
}
编辑:很抱歉,由于没有完成我到目前为止所做的工作,我一直在修补Array.Clear,但我想知道是否有其他方法可以在不使用内置方法的情况下清除它。
答案 0 :(得分:1)
有几种方法:
Array.Clear
(MSDN),它会将所有数组元素设置为默认值。
您可以编写自己的此方法版本:
void ClearArray<T>(T[] array)
{
for (int i = 0; i < array.Length; i++)
array[i] = default(T);
}
虽然实际上,我认为使用它没有任何价值,而不是预先存在的。你也可以创建一个 new 数组;虽然这是非常低效的,因为你必须为新数组分配内存,旧的数组留在内存中,直到垃圾收集器清理它。
scores = new int[10];
每种方法都会将您带到同一个地方,但我会使用Array.Clear
。