【问题标题】:Is there another way to check if an array is empty是否有另一种方法来检查数组是否为空
【发布时间】:2020-07-29 10:55:14
【问题描述】:

我添加了一个条件来检查数组是否为空,并自动将一个整数设置为大于数组的大小,因为它是空的,但我得到一个“索引超出了数组的范围”。改为消息

    public static bool hurdleJump(int[] hurdles, int jumpHeight)
    {
        int max = hurdles[0];

        if (hurdles == null && hurdles.Length == 0)
        {
            return false;
        }
        else if (hurdles != null || hurdles.Length >= 1)
        {
            for (int i = 0; i < hurdles.Length - 1; i++)
            {
                max = max < hurdles[i+1] ? hurdles[i+1] : max;
            }
            if (jumpHeight >= max)
            {
                return true;
            }
        }
            return false;
    }

    static void Main(string[] args)
    {
        Console.WriteLine(hurdleJump(new int[] {}, 7));
    }

【问题讨论】:

标签: c# arrays int


【解决方案1】:
  1. 在我们确保句柄不为空或不为空之后,将最大初始化移至。

  2. 将第一个 && 更改为 ||。

     public static bool hurdleJump(int[] hurdles, int jumpHeight)
     {
         if (hurdles == null || hurdles.Length == 0)
         {
             return false;
         }
         else
         {
             int max = hurdles[0];
             for (int i = 0; i < hurdles.Length - 1; i++)
             {
                 max = max < hurdles[i + 1] ? hurdles[i + 1] : max;
             }
             if (jumpHeight >= max)
             {
                 return true;
             }
         }
         return false;
     }
    

【讨论】:

  • 在“else”中不需要重新检查“if”的条件。你已经知道这不是真的
猜你喜欢
  • 2014-12-19
  • 1970-01-01
  • 2019-05-13
  • 2023-01-23
  • 1970-01-01
  • 2014-07-04
  • 1970-01-01
  • 1970-01-01
  • 2017-09-13
相关资源
最近更新 更多