Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialsumitanantwar
1,511 PointsError in for loop ?
Here we are trying to loop from the tapped index to the last index of the MutableList, simultaneously removing the elements from the List... So, for example...
var integers: MutableList<Int> = arrayListOf(0,1,2,3,4,5,6,7,8,9)
for (i in 5..integers.lastIndex)
{
integers.removeAt(i)
System.out.println(integers.toString())
}
LOOP 1-------------------
i = 5
integers = [0,1,2,3,4,6,7,8,9] // "5" at Index 5 removed
LOOP 2-------------------
i = 6
integers = [0,1,2,3,4,6,8,9] // "7" at Index 6 removed
LOOP 3-------------------
i = 7
integers = [0,1,2,3,4,6,8] // "9" at Index 7 removed
LOOP 4-------------------
i = 8
integers = [0,1,2,3,4,6,8] // Index 8 OUT OF BOUNDS
We should rather loop backwards
for (i in integers.lastIndex downTo 5)
{
integers.removeAt(i)
System.out.println(integers.toString())
}
Console -------------------
[0, 1, 2, 3, 4, 5, 6, 7, 8]
[0, 1, 2, 3, 4, 5, 6, 7]
[0, 1, 2, 3, 4, 5, 6]
[0, 1, 2, 3, 4, 5]
[0, 1, 2, 3, 4]
-----------------------------
2 Answers
Ben Deitch
Treehouse TeacherYep, that's correct! In the next two videos we add tests for adding/removing cards and we find/fix that bug :)
sumitanantwar
1,511 PointsYes! :) Just now watched those videos! I should had wondered. It would had been really weird to have missed such a blunder. Sorry for my impatience!
Anyways, the course content is great! Thanks for the efforts.