I've been going through some exam questions and stumbled upon two different implementations for a receipt selection task. I'm trying to understand the key differences between these two code snippets. The first code snippet is my own, and the second one is from the exam question.
Code Example 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;
}
Code Example 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;
}
I'd appreciate it if someone could shed light on this. What are the significant differences between the for loop structure in my Code Example 1 and the combination of for-each and while loops in Code Example 2? Is the inclusion of the else statement in my Code Example 1 necessary? Additionally, should I consider renaming the newReceipts array for better clarity?
And finally, does the code functionally achieve the same thing? My own code is Example 1, so in all likelihood, if there's an error, it would be there.
I received some valuable insights regarding the potential issues in my code. Specifically, there seems to be a bug in my first example's second loop where the newReceipts array might be of a shorter length compared to the receipts array, potentially leading to incorrect results.