【问题标题】:Nested If statements for checking eligbility用于检查资格的嵌套 If 语句
【发布时间】:2021-04-03 17:05:31
【问题描述】:

所以我对 C# 很陌生,在学习了一些基础知识后,我尝试制作一个简单的程序来使用 if 语句检查某人的资格。 该计划要求提供 3 项内容:年龄、身高和大学学位 您必须是 18 才能参加下一个问题,并且您必须高于 160 厘米 才能参加 CollegeDegree 问题。

现在程序运行良好,但是看它,我意识到有很多嵌套的 if 语句,代码很乱,不可读。

我需要怎么做才能让它更干净?我尝试按以下方式进行操作

if
else
if
else

但是,这会导致问题,如果第一个条件不满足,那么年龄小于 18 岁,它只会运行下一个 if 语句,而不是让用户不合格。

当前代码:

static void Main(string[] args)
        {
            int ageInput;
            int heightInput;
            bool hasCollegeDegree;
            
            
            Console.WriteLine("How old are you?");
            ageInput = Convert.ToInt32(Console.ReadLine());

            if (ageInput >= 18)
            {
                Console.WriteLine("You are older than 18");
                
                Console.WriteLine("How tall are you?");
                heightInput = Convert.ToInt32(Console.ReadLine());
                if (heightInput >= 160)
                {
                    Console.WriteLine("You are taller than 160cm");
                    
                    Console.WriteLine("Do you have a college degree?");
                    hasCollegeDegree = Convert.ToBoolean(Console.ReadLine());
                    if (hasCollegeDegree == true)
                    {
                        Console.WriteLine("You have a college degree");
                        Console.WriteLine("You are eligible");
                    }
                    else
                    {
                        Console.WriteLine("No College Degree");
                        Console.WriteLine("You are ineligible");
                    }
                }
                else
                {
                    Console.WriteLine("You are too short");
                }
            }
            else
            {
                Console.WriteLine("You are too young");
            }
        }

【问题讨论】:

  • 你是否也应该在每个else中写“你不合格”?
  • 不要忘记插入非数字值而不是年龄数字时会感到疼痛。使用 int.TryParse() 和 bool.TryParse() 代替。
  • 如果您使用嵌套的 if 语句,那么只有在外部条件为真时,才能满足内部条件。如果您完全删除嵌套,如果您真的希望它们嵌套,您可能会得到意想不到的结果.....@jjxtra 有一个很好的解决方案,但请记住刚才提到的警告。 jjxtra 的解决方案可以通过小的辅助方法进行重构,使其更具可读性。

标签: c# if-statement conditional-statements


【解决方案1】:

您可以使用反向条件退出代码。示例:

Console.WriteLine("How old are you?");
int ageInput = Convert.ToInt32(Console.ReadLine());
if (ageInput < 18)
{
    Console.WriteLine("You are too young");
    return;
}

Console.WriteLine("You are older than 18");

Console.WriteLine("How tall are you?");
int heightInput = Convert.ToInt32(Console.ReadLine());
if (heightInput < 160)
{
    Console.WriteLine("You are too short");
    return;
}

Console.WriteLine("You are taller than 160cm");

Console.WriteLine("Do you have a college degree?");
bool hasCollegeDegree = Convert.ToBoolean(Console.ReadLine());
if (!hasCollegeDegree)
{
    Console.WriteLine("No College Degree");
    Console.WriteLine("You are ineligible");
    return;
}

Console.WriteLine("You have a college degree");
Console.WriteLine("You are eligible");

【讨论】:

    【解决方案2】:

    我建议提取方法读取整数:

    private static int ReadInteger(string question) {
      while (true) {
        if (!string.IsNullOrWhiteSpace(question))
          Console.WriteLine(question);
    
        if (int.TryParse(Console.ReadLine(), out int result))
          return result;
    
        Console.WriteLine("Sorry, not a valid integer; please, try again.");
      }
    }
    

    和布尔值:

    private static HashSet<string> s_Yes = 
      new HashSet<string>(StringComparer.OrdinalIgnoreCase) {
        "Y", "Yes", "T", "True", "OK"
    };
    
    private static HashSet<string> s_No = 
      new HashSet<string>(StringComparer.OrdinalIgnoreCase) {
        "N", "No", "F", "False"
    };
    
    private static bool ReadBoolean(string question) {
      while (true) {
        if (!string.IsNullOrWhiteSpace(question))
          Console.WriteLine(question);
    
        string input = Console.ReadLine().Trim();
    
        if (s_Yes.Contains(input))
          return true;
        if (s_No.Contains(input))
          return false;
    
        Console.WriteLine("Sorry, not a valid value; please, try again.");
      }
    }
    

    那么你就可以放

    if (ReadInteger("How old are you?") < 18) {
      Console.WriteLine("You are too young");
    
      return;
    }
    
    Console.WriteLine("You are older than 18");
    
    if (ReadInteger("How tall are you?") < 160) {
      Console.WriteLine("You are too short");
    
      return;
    }
    
    Console.WriteLine("You are taller than 160cm");  
                    
    if (!ReadBoolean("Do you have a college degree (Y/N)?")) {
      Console.WriteLine("No College Degree");
      Console.WriteLine("You are ineligible");  
    
      return;  
    }
    
    Console.WriteLine("You have a college degree");
    Console.WriteLine("You are eligible");
    

    【讨论】:

      【解决方案3】:

      到目前为止,使用return 的答案的一个缺点是该方法已退出,因此您不能在同一方法中使用低于该点的任何代码。

      另一种方法是使用 COMPOUND 布尔语句并将所有条件组合成一个布尔表达式:

      if (ageInput >= 18 && heightInput >= 160 && hasCollegeDegree) 
      {
          Console.WriteLine("Congratulations! You meet the criteria.");
      }
      else
      {
          Console.WriteLine("You do not meet the criteria.");
      }
      

      如果您有许多不同的组合需要检查,这种检查方式可能会很有用。因此,用户预先输入所有信息,然后您可以进行一系列不同的复合检查,以查看他们满足哪些组合。也许您正在检查用户有资格获得列表中的哪些授权。

      有关&amp;&amp;||! 的更多信息,请参阅Boolean logical operators

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-06-01
        • 1970-01-01
        相关资源
        最近更新 更多