如何在Kotlin中循环两个不同大小的数组列表?

k4ymrczo  于 2023-05-01  发布在  Kotlin
关注(0)|答案(1)|浏览(85)

我试图从存储在数组列表中的firestore数据库中获取多个价格的值,并将它们相加以获得总价。问题是它们的大小不一样,我得到的是Java。lang.IndexOutOfBoundsException:索引:1,尺寸:1

while (name1.count() > i) {
  try {
    priceBreakdown += "option " + (i + 1).toString() + ":\n" + name1[i] + price1[contador] + "$\n"
    totalPrice += "price " + (i + 1).toString() + "=>\n" + (hotels[i] * days).toString() + "$\n"
    while (name2.count() > j) {
      priceBreakdown += "option " + (i + 1).toString() + "=>\n" + name2[j] + price2[j] + "&\n"
      totalPrice += "price " + (i + 1).toString() + "=>\n" + (Restaurants[j] * days).toString() + " Euros\n"
      j++
    }
    i++
  } catch (e: Exception) {
    Log.i(TAG, e.toString())
  }
}

我尝试了很多方法,但都没有成功。就像这样:

if (name1.count() > name2.count()) {
  while (name1.count() > i) {
    try {
      priceBreakdown += "option " + (i + 1).toString() + ":\n" + name1[i] + price1[contador] + "$\n"
      totalPrice += "price " + (i + 1).toString() + "=>\n" + (hotels[i] * days).toString() + "$\n"
      while (name2.count() > j) {
        priceBreakdown += "option " + (i + 1).toString() + "=>\n" + name2[j] + price2[j] + "&\n"
        totalPrice += "price " + (i + 1).toString() + "=>\n" + (Restaurants[j] * days).toString() + " Euros\n"
        j++
      }
      i++
    } catch (e: Exception) {
      Log.i(TAG, e.toString())
    }
  }
} else if (name2.count() > name1.count()) {
  while (name2.count() > i) {
    try {
      priceBreakdown += "option " + (i + 1).toString() + ":\n" + name1[i] + price1[contador] + "$\n"
      totalPrice += "price " + (i + 1).toString() + "=>\n" + (hotels[i] * days).toString() + "$\n"
      while (name2.count() > j) {
        priceBreakdown += "option " + (i + 1).toString() + "=>\n" + name2[j] + price2[j] + "&\n"
        totalPrice += "price " + (i + 1).toString() + "=>\n" + (Restaurants[j] * days).toString() + " Euros\n"
        j++
      }
      i++
    } catch (e: Exception) {
      Log.i(TAG, e.toString())
    }
  }
}

但它给了我同样的错误。

fdbelqdn

fdbelqdn1#

不要像这样手动循环集合,这违背了Kotlin中函数式编程的整个思想,Kotlin已经内置了对做你需要的事情的支持。
例如,如果你有两个int集合,你可以这样做:

val total = collectionOne.sum() + collectionTwo.sum()

或者,如果你有两个复杂类的集合,它们都有属性amount,你可以使用sumOf:

val total = collectionOne.sumOf{it.amount} + collectionTwo.sumOf{it.amount}

作为Kotlin的一般经验法则,如果你使用var作为一个总数,然后手动循环一个集合,你可能做错了,可以使用内置的集合函数来代替。

相关问题