美文网首页
每日一练90——Java数绵羊......(8kyu)

每日一练90——Java数绵羊......(8kyu)

作者: 砾桫_Yvan | 来源:发表于2018-09-05 10:47 被阅读0次

    题目

    考虑一群绵羊可能会从他们的地方遗失一些羊。我们需要一个函数来计算数组中存在的绵羊数量(true表示存在)。

    例如,

    [true, true, true, false,
    true, true, true, true ,
    true, false, true, false,
    true, false, false, true ,
    true, true, true, true ,
    false, false, true, true]
    正确答案是17。

    提示:不要忘记检查像null/ 这样的错误值undefined。

    测试用例:

    import org.junit.Test;
    import static org.junit.Assert.assertEquals;
    import org.junit.runners.JUnit4;
    
    
    public class CounterTest {
        Boolean[] array1 = {true,  true,  true,  false,
                          true,  true,  true,  true ,
                          true,  false, true,  false,
                          true,  false, false, true ,
                          true,  true,  true,  true ,
                          false, false, true,  true };
    
        @Test
        public void test() {
          assertEquals("There are 17 sheeps in total", 17, new Counter().countSheeps(array1));
        }
    }
    

    解题

    My

    public class Counter {
      public int countSheeps(Boolean[] arrayOfSheeps) {
          int j = 0;
          for (Boolean arrayOfSheep : arrayOfSheeps) {
              if (arrayOfSheep != null) {
                  if (arrayOfSheep) {
                      j++;
                  }
              }
          }
          return j;
      }
    }
    

    Other

    public class Counter {
      public int countSheeps(Boolean[] arrayOfSheeps) {
        int counter = 0;
        for (Boolean present : arrayOfSheeps) {
          if (present != null && present) {
            counter += 1;
          }
        }
        return counter;
      }
    }
    

    后记

    题目经过改动,大部分答案都不适用现在的null值,但是上面这个条件判断我怎么没想到把条件合起来呢。

    相关文章

      网友评论

          本文标题:每日一练90——Java数绵羊......(8kyu)

          本文链接:https://www.haomeiwen.com/subject/ulnowftx.html