【问题标题】:Go to line/loop switch statement?转到行/循环切换语句?
【发布时间】:2020-10-04 17:44:42
【问题描述】:

我什至不知道该怎么称呼我想做的事... 基本上我有一个选择屏幕并使用 switch 语句而不是 if/else,在 switch 语句的默认部分我想要求确认退出...... 基本上

switch(input)
{
    default:
        Console.WriteLine("Are you sure?")
        var confirm = Console.ReadLine();

        switch (confirm)
        {
            case "y":
                //quit
            case "n":
                break;
            default:
                // GO BACK TO Console.WriteLine();
                break;
        }

        break;
}

基本上我需要回到 Console.WriteLine();部分,但我不确定最有效的方法是什么?

【问题讨论】:

  • 你想要的是一个while循环...initialize with 'no'; while (user says no) { ask for confirmation; if user says yes break loop; }

标签: c# console-application


【解决方案1】:
  1. 第一个 switch 语句完全没有用,因为只有一个默认值。

  2. 我不知道// GO BACK TO Console.WriteLine(); 是什么意思(在哪里???!)但我猜你想做这样的事情:

     boolean toExit = false;
     while (!toExit) {
     // And for what is the input??
     string input = Console.ReadLine();
    
     Console.WriteLine("Are you sure?")
     var confirm = Console.ReadLine();
    
     switch (confirm)
     {
         case "y":
             toExit = true;
             break;
         case "n":
             break;
         default:
             // GO BACK TO Console.WriteLine();
            // SO, WHERE?
             break;
     }
    

}

【讨论】:

  • 1.抱歉,我没有写出我的 15 case switch 语句给你,它没有用的信息,浪费时间让别人阅读它。 2. 字面意思是:整篇文章的第 7 行,代码中的第 4 行。
【解决方案2】:

如果我想在控制台应用程序中实现一些交互性,我通常会创建一堆 Control 类(类似于 WinForms,具有一堆不同的功能,如颜色/对齐/等)。要提示控制台对话框以简单回答是/否,您可以使用简单的方法:

public static bool PromptYesNoDialog(string question)
{
    Console.WriteLine(question);
    while(true)
    {
        var answer = Console.ReadLine().Trim().ToLower();
        if(answer.Equals("y") || answer.Equals("yes"))
            return true;
        if(answer.Equals("n") || answer.Equals("no"))
            return false;
        Console.WriteLine("Answer should be 'y' or 'n'.");
    }
}

然后使用它:

   //doing work, and encountered problem which only user can solve
   if(PromptYesNoDialog("Do you wanna play?"))
   {
      //play
   }
   else
   {
      //not play
   }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多