使用indexof的索引超出范围异常

时间:2019-05-04 17:40:37

标签: java arrays scala indexing

def toLowerCase(str: String): String = {
        val lowerCase = "abcdefghijklmnopqrstuvwxyz".split("")
        val upperCase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".split("")
        var returnStr = ""

        str.split("").foreach(c => if (lowerCase.contains(c)) returnStr += c 
                else returnStr += lowerCase(upperCase.indexOf(c)))

        returnStr
    }

此代码段导致

java.lang.ArrayIndexOutOfBoundsException: -1

不确定在这种情况下是什么导致索引-1传递

1 个答案:

答案 0 :(得分:3)

indexOf可以返回-1str不仅可以包含拉丁字母)。

  /** Finds index of first occurrence of some value in this $coll.
   *
   *  @param   elem   the element value to search for.
   *  @tparam  B      the type of the element `elem`.
   *  @return  the index of the first element of this $coll that is equal (as determined by `==`)
   *           to `elem`, or `-1`, if none exists.
   *
   *  @usecase def indexOf(elem: A): Int
   *    @inheritdoc
   *
   *    $mayNotTerminateInf
   *
   */
  def indexOf[B >: A](elem: B): Int = indexOf(elem, 0)