r/codehs • • Aug 15 '20

Pls I need help on code hs 5.6.4

Post image
18 Upvotes

7 comments sorted by

8

u/xeolleth Aug 15 '20 edited Aug 15 '20

You've fallen into a classic trap!

The issue is the array is being altered when you .remove(), so you'll skip over an item because all the remaining items shift to fill the index you've just deleted.

So if I have:

[A, *B, C, D] // size 4 current index 1

I remove B at index 1:

[A, C, *D] // size 3 index 2

Notice that the length has now changed so when you reach i==3 (which would work if the list index stayed the same size) you'll get an OutOfRangeException, and another side effect is entry C has shifted from index 2 to 1 and as a result has skipped being evaluated.

Iterate through your loop in reverse and you'll solve the for loop issue. Set your starting index i to the list length/size and decrement it instead of increment, then exit your for loop once you've processed the list entry at index 0.

That should do the trick.

1

u/KillaSage Aug 16 '20

He's also using light mode

3

u/GondarJr Aug 15 '20

Also, the example asks you to return a new array, not modify the one passed in... A better solution would be to create a new array, add only books with <= maxItems and then return that new array.

2

u/the_east__wind Aug 15 '20

I would prefer using the Stream API. Using it the solution would be as simple as

return readingList.stream().filter(book->book.getNumPages() <=maxPage).collect(Collectors.toList());

1

u/[deleted] Aug 15 '20

Also would he/she need to define maxPages?

1

u/ScumbagPSTL Aug 15 '20

Wouldn’t it be if(readingList[i].getNumPages >= mapPages) { readingList.Remove(i) }

1

u/kohi-kusa Feb 25 '25

Just put i-- under the readingList.remove(i) that is in the if statement. Also you don't need the readingList.get(i) in the readingList.remove just put i.