Find last occurrence of a String in array using Kotlin
For your question of finding the first and last occurrences in an Array there is no need to use a for-loop at all in Kotlin, you can simply use indexOf and lastIndexOf
As for throwing an error you can throw an Exception if indexOf returns -1
, observe:
import java.util.Arrays
fun main(args: Array<String>) {
// Declaring array
val wordArray = arrayOf("cat", "dog", "lion", "tiger", "dog", "rabbit")
// Declaring search word
var searchWord = "dog"
// Finding position of first occurence
var firstOccurence = wordArray.indexOf(searchWord)
// Finding position of last occurence
var lastOccurence = wordArray.lastIndexOf(searchWord)
println(Arrays.toString(wordArray))
println("\"$searchWord\" first occurs at index $firstOccurence of the array")
println("\"$searchWord\" last occurs at index $lastOccurence of the array")
// Testing something that does not occur in the array
searchWord = "bear"
var index = wordArray.indexOf(searchWord)
if (index == -1) throw Exception("Error: \"$searchWord\" does not occur in the array")
}
Output
[cat, dog, lion, tiger, dog, rabbit]
"dog" first occurs at index 1 of the array
"dog" last occurs at index 4 of the array
java.lang.Exception: Error: "bear" does not occur in the array