Layman
Layman

Reputation: 1056

Index out of bounds exception with indexof

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
    }

This code snippet causes

java.lang.ArrayIndexOutOfBoundsException: -1

Not sure what would cause an index of -1 being passed in this scenario

Upvotes: 1

Views: 568

Answers (1)

Dmytro Mitin
Dmytro Mitin

Reputation: 51658

indexOf can return -1 (str can contain not only latin letters).

  /** 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)

Upvotes: 3

Related Questions