Iterator - next() - loop run uncompleted

Why miss does the last loop with the input “150 144 220 170”?
result:
You can go!
Sorry, not today
You can go!

fun checkHeight(iterator: Iterator<Int>) {
    while (iterator.hasNext()) {
        if(iterator.next() < 145 || iterator.next() > 210) {
            println("You can go!")
        } else {
            println("Sorry, not today")
        }
    }
}

fun main() {
    val list = readln().split(" ").map(Integer::parseInt).toList()
    checkHeight(list.iterator())
}

You are calling iterator.next() twice in a same iteration. What you should had done is this:

fun checkHeight(iterator: Iterator<Int>) {
    while (iterator.hasNext()) {
        val height = iterator.next()
        if (height < 145 || height > 210) {
            println("You can go!")
        } else {
            println("Sorry, not today")
        }
    }
}

but this is probably even better:

fun checkHeight(iterator: Iterator<Int>) {
    for (height in iterator) {
        if (height < 145 || height > 210) {
            println("You can go!")
        } else {
            println("Sorry, not today")
        }
    }
}

BTW, it is not very common to create APIs accepting/returning iterators. If you don’t have a good reason to do this, it usually makes more sense to accept Iterable instead.

2 Likes