需要澄清:两个收据选择代码片段之间的核心区别

Clarification needed: core differences between two receipt selection code snippets

提问人:Bishop_1 提问时间:8/10/2023 最后编辑:Mark RotteveelBishop_1 更新时间:8/10/2023 访问量:19

问:

我一直在研究一些考试问题,偶然发现了收据选择任务的两种不同实现。我正在尝试理解这两个代码片段之间的主要区别。第一个代码片段是我自己的,第二个代码片段来自考试问题。

代码示例 1:

public static Receipt[] selectReceipts(Receipt[] receipts, String currency) {

    int countReceipts = 0;
    for (int i = 0; i < receipts.length; i++) {
        if (receipts[i].getCurrency().equals(currency)) {
            countReceipts++;
        } else {
            i++; 
        }
    }

    Receipt[] newReceipts = new Receipt[countReceipts];

    for (int i = 0; i < receipts.length; i++) {
        if (receipts[i].getCurrency().equals(currency)) {
            newReceipts[i] = receipts[i];
        }
    }

    return newReceipts; 
}

代码示例 2:

public static Receipt[] selectReceipts(Receipt[] receipts, String currency) {

    int countReceipts = 0;
    for (Receipt receipt : receipts) {
        if (receipt.getCurrency().equals(currency)) {
            countReceipts++;
        }
    }

    Receipt[] selectedReceipts = new Receipt[countReceipts];
    int i = 0;
    int j = 0;
    while (j < countReceipts) {
        if (receipts[i].getCurrency().equals(currency)) {
            selectedReceipts[j++] = receipts[i];
        }
        i++;
    }

    return selectedReceipts;
}

如果有人能阐明这一点,我将不胜感激。代码示例 1 中的循环结构与代码示例 2 中的 and 循环组合之间有什么显著区别?是否有必要在我的代码示例 1 中包含该语句?此外,我是否应该考虑重命名数组以获得更好的清晰度?forfor-eachwhileelsenewReceipts

最后,代码在功能上是否实现了相同的目标?我自己的代码是示例 1,所以很有可能,如果有错误,它就会在那里。

我收到了一些关于代码中潜在问题的宝贵见解。具体来说,在我的第一个示例的第二个循环中似乎存在一个错误,与 receipts 数组相比,newReceipts 数组的长度可能更短,这可能会导致不正确的结果。

Java 比较 代码分析

评论

0赞 8/10/2023
您自己的代码中有几件事可能会使您出现“数组越界”错误。需要删除“else”语句,因为它会导致在盘点时跳过收据。其次,语句 “newReceipts[i] = receipts[i]” 需要更改为 “newReceipts[j++] = receipts[i]”,其中 j 应该在 for 循环之前定义并初始化为 0。

答: 暂无答案