我正在嘗試創建一個 kotlin 函式,該函式給出一個數字串列和另一個單獨的數字,將遍歷串列,從每個元素中減去一個,然后在滿足條件時在串列末尾添加另一個元素。這是我的代碼:
fun listCalculator(myList:MutableList<Int>, number:Int) {
for (i in 0..number){
val iterator = myList.listIterator()
for (item in iterator) {
item -= 1
if (item == 0) {iterator.add(10)}
println(myList.toString())
}}}
這是我傳遞給函式的串列:
var testList:MutableList<Int> = mutableListOf(1,7,0,1)
我碰上第一個錯誤是在第5行,當我嘗試從的值中減去1 item:'Val cannot be reassigned'。我10遇到的第二個問題是這段代碼在滿足(item == 0)條件的元素之后添加了新元素,但我希望它在串列的末尾。
uj5u.com熱心網友回復:
首先,當迭代一個集合時,我們不會收到某種指向當前專案的指標。item在您的示例中只是當前專案的副本,修改它不會影響串列。這是item只讀的原因之一- 否則會產生誤導,因為開發人員會認為他們修改了串列,但實際上他們不會。為了替換當前專案,我們必須使用ListIterator.set()或使用其索引訪問專案。
其次,在迭代同一個集合的同時在最后添加新專案會很棘手。在我們完成迭代后,記住0專案的數量并添加10專案要容易得多。
解決方案使用ListIterator.set():
fun listCalculator(myList: MutableList<Int>, number: Int) {
for (i in 0..number) {
var counter = 0
val iterator = myList.listIterator()
for (item in iterator) {
iterator.set(item - 1)
if (item == 1) {
counter
}
}
repeat(counter) { myList = 10 }
}
}
我們迭代索引并手動訪問當前專案的解決方案:
fun listCalculator(myList: MutableList<Int>, number: Int) {
for (i in 0..number) {
var counter = 0
for (index in myList.indices) {
val item = --myList[index]
if (item == 0) {
counter
}
}
repeat(counter) { myList = 10 }
}
}
還要注意,外回圈不是運行number時間,而是number 1時間。如果您打算number多次執行它,那么您必須使用for (i in 0 until number) { ... }或僅:repeat(number) { ... }
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/394051.html
上一篇:Arduino ESP32 Blinker 畢業設計 課程設計 DIY 003——基于ESP32的嬰兒提醒的設計與制作
