我正在编写一个成绩计算器,最后,我问用户他们是否有另一个成绩要计算。
Console.Write("Do you have another grade to calculate? ");
moreGradesToCalculate = Console.ReadLine();
moreGradesToCalculate = moreGradesToCalculate.ToUpper();
我想显示一个包含"是"或"否"选项的对话框。
如果 DialogResult 为"是",我希望能够再次运行该程序,如果结果为"否",则执行其他操作。
你应该使用 do...while(...)
循环。
我认为再次运行整个程序不是一个好主意,只需重新开始获取用于计算成绩的数字(将您的代码包装在一个循环中)。
对于对话框,只需导入程序集System.Window.Forms
并使用它:
DialogResult result = MessageBox.Show("Do you want to start over?", "Question", MessageBoxButtons.YesNo);
if (result == DialogResult.No) {
// TODO: Exit the program
}
你可以使用do/while
这样的结构
do {
Console.Write("Do you have another grade to calculate Y/N? ");
var moreGradesToCalculate = Console.ReadLine().ToUpper();
if(moreGradesToCalculate == "Y")
//do something
else if(moreGradesToCalculate == "N")
break;
}while(true);
如果需要对话框,则必须添加对System.Windows.Forms
的引用,并在文件顶部为同一命名空间添加using
语句。然后,您只需检查在 Do-While 循环结束时对MessageBox
对象调用 Show
方法的结果。例如:
do
{
// Grading calculation work...
}
while (MessageBox.Show("Do you have another grade to calculate?",
"Continue Grading?", MessageBoxButtons.YesNo) == DialogResult.Yes);
这将一直循环,直到用户单击"否"。
如果您不想继续使用鼠标,请在命令行上执行以下操作:
ConsoleKeyInfo key = new ConsoleKeyInfo();
do
{
// Grading work...
Console.WriteLine("nDo you want to input more grades? (Y/N)");
do
{
key = Console.ReadKey();
}
while (key.Key != ConsoleKey.Y && key.Key != ConsoleKey.N);
}
while (key.Key == ConsoleKey.Y);
这是关于循环的参考资料的链接 - 或来自Microsoft的"迭代语句"。Do-While
是你在刚开始时应该尝试背诵的少数
http://msdn.microsoft.com/en-us/library/32dbftby.aspx