kotlin Exception「Exception in thread “main” java.util.NoSuchElementException」の解決方法

kotlinで、Exception「Exception in thread “main” java.util.NoSuchElementException」の解決方法を記述してます。「next()」をListにある数より大きい回数で実行した場合などに発生します。
環境
- OS windows11 home
- java 19.0.1
- kotlin 1.7.20-release-201
エラー全文
以下のコードで発生。
fun main() {
var mlist = mutableListOf("aaa", "bbb", "ccc")
val itr = mlist.iterator()
println(itr.next())
println(itr.next())
println(itr.next())
println(itr.next())
}
Exception
※ファイル名は「hello.kt」
Exception in thread "main" java.util.NoSuchElementException
at java.base/java.util.ArrayList$Itr.next(ArrayList.java:970)
at HelloKt.main(hello.kt:9)
at HelloKt.main(hello.kt)
原因
Listにある数より多く「next()」を実行したため
対処法
「hasNext」を使用して、範囲内でじっこうする
fun main() {
var mlist = mutableListOf("aaa", "bbb", "ccc")
val itr = mlist.iterator()
while (itr.hasNext()) {
println(numbersIterator.next())
}
}
実行結果

-
前の記事
Android Studio ブロック単位で選択するショートカットキー 2023.10.31
-
次の記事
npm エラー「npm ERR! notsup Unsupported platform for n@9.2.0: wanted {“os”:”!win32″} (current: {“os”:”win32″})」の解決方法 2023.10.31
コメントを書く