如果满足条件,如何忽略一行代码/代码块?

时间:2020-05-04 23:56:13

标签: c# .net

如果满足条件,是否可以忽略一行代码/代码块? 我正在做C#.NET教程,该应用程序是一个猜数字游戏。

我添加了一个提示选项,如果用户输入了错误的数字(否则输入):

// While guess is not correct
            while (guess != correctNumber)
            {
                //Get users input
                string input = Console.ReadLine();

                // Make sure it's a number
                if (!int.TryParse(input, out guess))
                {
                    // Print error message
                    PrintColorMessage(ConsoleColor.Red, "Please use an actual number");

                    // Keep going
                    continue;
                }

                // Cast to int and put in guess
                guess = Int32.Parse(input);

                // Check if guess is close to correct number
                if(guess == correctNumber + 2 || guess == correctNumber - 2)
                {
                    // Tell the user that he is close
                    PrintColorMessage(ConsoleColor.DarkCyan, "You are close!!");

                }
                // Match guess to correct number
                else if (guess != correctNumber)
                {
                    // Print error message
                    PrintColorMessage(ConsoleColor.Red, "Wrong number, please try again");

                    AskForAHint(correctNumber);
                }
            }

            // Print success message 
            PrintColorMessage(ConsoleColor.Yellow, "You are CORRECT!");

基本上,我是在问用户是否要提示,如果他写了Y,则将显示提示。但是,是否有一个选项仅一次显示此问题,因为此if语句包含在 while 循环中? 如果“您要提示吗?”会很烦人。即使用户说是,问题也会一直显示。

我的AskForAHint函数:

static void AskForAHint(int num)
    {
        // Ask user if he wants a hint
        Console.WriteLine("Do you want a hint? [Y/N]");

        // Take his answer
        string ans = Console.ReadLine().ToUpper();

        // If the user wants a hint
        if (ans == "Y")
        {
            // First hint number
            int beginning = (num - num % 10);
            // Second hint number
            int finish = beginning + 10;
            // Give user a hint
            Console.WriteLine("The correct number is somewhere betweer {0} and {1}", beginning, finish);
        }
        else if (ans == "N")
        {
            return;
        }
    }

谢谢

3 个答案:

答案 0 :(得分:2)

我认为您可以通过计数器执行“如果”操作。 试试吧

        Int cont = 0; //global
        // While guess is not correct
        while (guess != correctNumber)
        {
            //Get users input
            string input = Console.ReadLine();

            // Make sure it's a number
            if (!int.TryParse(input, out guess))
            {
                // Print error message
                PrintColorMessage(ConsoleColor.Red, "Please use an actual number");

                // Keep going
                continue;
            }

            // Cast to int and put in guess
            guess = Int32.Parse(input);

            // Check if guess is close to correct number
            if(guess == correctNumber + 2 || guess == correctNumber - 2)
            {
                // Tell the user that he is close
                PrintColorMessage(ConsoleColor.DarkCyan, "You are close!!");

            }
            // Match guess to correct number
            else if (guess != correctNumber)
            {
                // Print error message
                PrintColorMessage(ConsoleColor.Red, "Wrong number, please try again");
              if(cont == 0){
                AskForAHint(correctNumber);
              }
            }
        }

        // Print success message 
        PrintColorMessage(ConsoleColor.Yellow, "You are CORRECT!");

然后在函数中添加

static void AskForAHint(int num)
{
    // Ask user if he wants a hint
    Console.WriteLine("Do you want a hint? [Y/N]");

    // Take his answer
    string ans = Console.ReadLine().ToUpper();

    // If the user wants a hint
    if (ans == "Y")
    {
        cont = 1;
        // First hint number
        int beginning = (num - num % 10);
        // Second hint number
        int finish = beginning + 10;
        // Give user a hint
        Console.WriteLine("The correct number is somewhere betweer {0} and {1}", beginning, finish);
    }
    else if (ans == "N")
    {
        return;
    }
}

答案 1 :(得分:2)

另一种方法是使提示数量可配置(允许调用者指定他们要让用户要求的提示数量),然后跟踪方法本身给出的提示数量

这将需要对AskForAHint方法进行一些更改,因为我们不知道用户是否对提示问题回答“ Y”或“ N”。由于AskForHint没有返回值,我们可以让它返回一个bool来指示用户如何回答问题:

static bool AskForAHint(int num)
{
    var answer = GetUserInput("Do you want a hint? [Y/N]: ", ConsoleColor.Yellow);

    if (!answer.StartsWith("Y", StringComparison.OrdinalIgnoreCase))
    {
        return false;
    }

    var beginning = num - num % 10;
    var finish = beginning + 10;
    Console.WriteLine($"The correct number is somewhere between {beginning} and {finish}");

    return true;
}

现在,我们可以通过在“游戏”方法中增加一个计数器来跟踪用户收到了多少个提示:

// Only ask for a hint if they have any hints (and guesses) remaining
if (hintCount < maxHints && guessCount < maxGuesses)
{
    // If they asked for a hint, increase the hint count
    if (AskForAHint(correctNumber)) hintCount++;
    // If they didn't want a hint, max out hint count so we don't ask again
    else hintCount = maxHints; 
}

为了测试上面的示例代码,我在下面使用了此方法,该方法还使我们能够配置用户的总猜测数,范围的最小值和最大值以及是否应给它们“方向提示”,例如“太高!”或“太低了!”:

private static readonly Random Random = new Random();

private static void PlayGuessingGame(int maxHints = 1, int maxGuesses = 10, 
    int rangeMin = 1, int rangeMax = 100, bool giveDirectionalHint = true)
{
    if (rangeMax < rangeMin) rangeMax = rangeMin;
    var correctNumber = Random.Next(rangeMin, rangeMax + 1);
    var guessCount = 0;
    var hintCount = 0;

    WriteMessage("Welcome to the guessing game!", ConsoleColor.White);
    WriteMessage("-----------------------------\n", ConsoleColor.White);
    WriteMessage($"I'm thinking of a number from {rangeMin} to {rangeMax}. ", ConsoleColor.Green);
    WriteMessage("Let's see how many guesses it takes you to guess it!\n", ConsoleColor.Green);

    do
    {
        WriteMessage($"(You have {maxGuesses - guessCount} guesses left)");
        var input = GetUserInput("Enter the number I'm thinking of: ", ConsoleColor.White);

        int guess;

        if (!int.TryParse(input, out guess))
        {
            WriteMessage("Please enter a whole number", ConsoleColor.Red);
            continue;
        }

        // Only increment guesses if they entered an actual number
        guessCount++;

        if (guess == correctNumber) break;

        if (Math.Abs(guess - correctNumber) == 2)
        {
            WriteMessage("You are close!!", ConsoleColor.DarkCyan);
        }

        if (giveDirectionalHint)
        {
            WriteMessage("Wrong number - too " + (guess < correctNumber ? "low!" : "high!"),
                ConsoleColor.Red);
        }
        else
        {
            WriteMessage("Wrong number, please try again", ConsoleColor.Red);
        }

        // Only ask for a hint if they have any hints (and guesses) remaining
        if (hintCount < maxHints && guessCount < maxGuesses)
        {
            // If they asked for a hint, increase the hint count
            if (AskForAHint(correctNumber)) hintCount++;
            // If they didn't want a hint, max out hint count so we don't ask again
            else hintCount = maxHints; 
        }
    } while (guessCount < maxGuesses);

    WriteMessage("You are CORRECT!", ConsoleColor.Yellow);

    GetKeyFromUser("\nDone! Press any key to exit...");
}

这使用了辅助功能:

public static void WriteMessage(string message, ConsoleColor color = ConsoleColor.Gray)
{
    Console.ForegroundColor = color;
    Console.WriteLine(message);
    Console.ResetColor();
}

private static string GetUserInput(string prompt, ConsoleColor color = ConsoleColor.Gray)
{
    Console.ForegroundColor = color;
    Console.Write(prompt);
    Console.ResetColor();
    return Console.ReadLine();
}

输出

您可以在下面的输出中看到,只有一个提示。但是,结合方向性提示,游戏就很容易获胜:

enter image description here

答案 2 :(得分:0)

使用成员变量布尔值,类似于避免递归调用的方式。

private bool alreadyHinted = false;
static void AskForAHint(int num)
    {
         if (alreadyHinted) return;
         alreadyHinted = true;

有时,您需要将alreadyHinted设置回false