c# - 如果没有更多代码要使用 'else' 执行,如何关闭 IF 语句?

标签 c#

在我的初学者 secret 文字游戏中,假设游戏已经结束但还有更多不相关的代码要遵循,以“else {}”结束最终的 if 语句(如我代码的末尾)是最好的移动方式接下来是什么代码?或者此后的任何内容是否需要包含在 else 的 {} 中?初学者,欢迎批评!

        string secretWord = "Catatonic";
        string guess = "";
        int guessCount = 0;
        int guessLimit = 3;
        bool outOfGuesses = false;
        bool firstGuess = false;

        Console.WriteLine("Guess the secret word: ");
            guess = Console.ReadLine();
        guessCount++;
        if (guess == secretWord)
        {
            Console.WriteLine("You win!");
            firstGuess = true;  
        }
        else

            do
                if (guessCount < guessLimit)
                {
                    Console.WriteLine("Wrong answer, try again: ");
                    guess = Console.ReadLine();
                    guessCount++;
                }
                else
                {
                    outOfGuesses = true;
                } while (guess != secretWord && !outOfGuesses);

                if (guess != secretWord && outOfGuesses)
        {
            Console.WriteLine("You're out of guesses mate");
        }
        else if (!firstGuess)
        {
            Console.WriteLine("You're a winner!");
        }
        else {}

最佳答案

ifelse 后跟单个语句或代码块内的一个或多个语句,{ }

忘掉单个语句并始终使用 {},您只需学习 1 种模式:

 if (a == b)
 {
    // code for a == b
 }
 else
 {
    // code for a != b
 }

else{} 部分是可选的。

同样的建议也适用于 do while,始终使用 {}:

do
{
   // code to repeat   
}
while(x < y)

关于c# - 如果没有更多代码要使用 'else' 执行,如何关闭 IF 语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56039609/

相关文章:

c# - 找不到类型或命名空间名称 'Keyless' ef

c# - 狗以相同的速度前进

c# - 在 C# + PHP 中使用命名管道进行进程间通信

c# - TaskCompletionSource.SetResult 的线程安全

c# - IronPython 无法导入模块 cv2 (OpenCV)

c# - 自动完成扩展程序未填充

c# - 如何在循环中修改队列集合?

使用 System.Security.Cryptography.Aes 的 AES256 加密的 C# 示例

c# - 在 C# 中读取 Java UUID(从 DB)

c# - 整个工具提示的背景色