【问题标题】:If Yes button of Dialog box is clicked, run program again如果单击对话框的“是”按钮,请再次运行程序
【发布时间】:2012-08-12 16:27:28
【问题描述】:

我正在写一个成绩计算器,最后我问用户是否还有其他成绩要计算。

 Console.Write("Do you have another grade to calculate? ");
        moreGradesToCalculate = Console.ReadLine();
        moreGradesToCalculate = moreGradesToCalculate.ToUpper();

我想显示一个带有是或否选项的对话框。

如果 DialogResult 为 Yes,我希望能够再次运行该程序,如果结果为 No,则执行其他操作。

【问题讨论】:

    标签: c#


    【解决方案1】:

    您应该使用do...while(...) 循环。

    【讨论】:

      【解决方案2】:

      我认为再次运行整个程序不是一个好主意,只需重新获取用于计算成绩的数字(将您的代码包装在一个循环中)。

      对于对话框,只需导入 System.Window.Forms 程序集并使用它:

      DialogResult result = MessageBox.Show("Do you want to start over?", "Question", MessageBoxButtons.YesNo);
      
      if (result == DialogResult.No) {
          // TODO: Exit the program
      }
      

      【讨论】:

        【解决方案3】:

        你可以使用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);
        

        【讨论】:

        • while(1) 在 C# 中?而且我个人不喜欢这种编码风格,为什么写一个while(true) 而while(moreGradesToCalculate == "Y") 已经绰绰有余了?
        • @BlackBear:在您的情况下,您需要声明while 循环的moreGradesToCalculate outside,在我的情况下,我可以避免在它之外声明状态变量。在 this 的情况下,没有输赢之分,只是编码风格的问题。
        • @Tigran 恕我直言,您也没有在循环内声明moreGradesToCalculate。您在声明中缺少 varstring 或其他类型。
        【解决方案4】:

        如果您想要一个对话框,则必须添加对 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

        【讨论】:

          猜你喜欢
          • 2020-10-25
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多