【问题标题】:Can't get this piece of code to pass. Can someone please help me [duplicate]无法让这段代码通过。有人可以帮我吗[重复]
【发布时间】:2021-07-30 06:31:36
【问题描述】:

我不知道为什么这段代码没有通过。

如果每个子列表都按升序排列,则返回 true,否则返回 false。

public static boolean allSubListsAscending(ArrayList<ArrayList<Integer>> list) {

        for (ArrayList<Integer> intList : list) {
            for (int j = 0; j < intList.size() - 1; j++) {
                if (intList.get(j) > intList.get(j + 1))
                    return false;
            }

        }
        return true;
}

@Test @Graded(description="AllSubListsAscendingComprehensive")
    public void testAllSubListsAscendingComprehensive() {
        testAllSubListsAscendingBasic();
        assertFalse(ListOfListService.allSubListsAscending(null));
        assertFalse(ListOfListService.allSubListsAscending(list4_nullItems));

        ArrayList<ArrayList<Integer>> ascending = new ArrayList<ArrayList<Integer>>();
        ascending.add(new ArrayList<Integer>(Arrays.asList(10, 20, 70, 90)));
        ascending.add(new ArrayList<Integer>(Arrays.asList(100, 110, 120, 130)));
        ascending.add(null);
        ascending.add(new ArrayList<Integer>(Arrays.asList(10, 20, 70, 90)));
        assertFalse(ListOfListService.allSubListsAscending(ascending));

        currentMethodName = new Throwable().getStackTrace()[0].getMethodName();
    }

【问题讨论】:

  • 请发布 SSCCE。您可以从这里阅读它的内容:sscce.org
  • 添加 if(list ==null) return false;在你方法的开始。如果(intList ==null)返回false;在你的第一个 for 循环中
  • +1 表示 sscce。但是,第一个测试用例会导致您的方法抛出空指针异常,而不是返回 false。

标签: java arraylist sub-array


【解决方案1】:

您的子列表中有 null 值,但您没有在 allSubListsAscending 中处理 null 大小写。

allSubListsAscending 方法应该是这样的:

    public static boolean allSubListsAscending(ArrayList<ArrayList<Integer>> list) {

    if(null == list){
        return false;
    }
    for (ArrayList<Integer> intList : list) {
        if(null==intList){
            return false;
        }
        for (int j = 0; j < intList.size() - 1; j++) {
            if (intList.get(j) > intList.get(j + 1))
                return false;
        }

    }
    return true;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-14
    • 2015-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-04
    • 2021-08-12
    相关资源
    最近更新 更多