6

I have this array: ["cat", "dog", "lion", "tiger", "dog", "rabbit"]

  • How can I find the position of the first "dog"?

  • How can I find the position of last "dog"?

  • How can I throw an error when I search for something that is not in the array?

Currently I have a for loop but I am having difficulty with making it print the position.

2
  • Also can you clarify if you have a list or an array? Commented Sep 10, 2017 at 8:03
  • 1
    I have a array of string Commented Sep 10, 2017 at 8:05

3 Answers 3

8

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
Sign up to request clarification or add additional context in comments.

Comments

1

@shash678 has given what a most useful answer, but more could be useful depending on more about the nature of your question.

Specifically: Are you seeking an answer to the exact problem stated, or looking to learn kotlin?

I have this array: ["cat", "dog", "lion", "tiger", "dog", "rabbit"]

But do you specifically need an Array? In kotlin, this case would normally be coded as a List, so

  val wordList = listOf("cat", "dog", "lion", "tiger", "dog", "rabbit")

The list is 'immutable' and generally List (or when needed MutableList) are used in Kotlin unless there are other reasons such as compatibility with existing code or in the case of MutableList, specific performance requirements.

Further, if your question is more "How do I solve this problem using a for loop with indexes?", then code like this:

val wordList = listOf("cat", "dog", "lion", "tiger", "dog", "rabbit")
fun List<String>.findWord( target:String):Pair<Int,Int>?{
    var (first,last) = Pair(-1,-1)
    for(idx in this.indices){
        if(this[idx]==target){
            last = idx
            if(first ==-1) first = idx
        }
    }
    return if(first>-1) Pair(first,last) else null
}
println("result ${wordList.findWord("dog")!!}")

Not at all the best way to solve the specific problem, but may be of use for anyone wondering "How to access index values within a for loop", rather than solve this specific problem. So this is an example of kotlin coding rather than a recommended solution to this problem.

The last part of the question was "How I throw an error when I search for something that is not in the array?".

The kotlin 'idiom' is to return null on failure and use the null safety to handle the error. This code simply raises an exception if null is returned. That is not very information, but using ?: throw MyException("Oops") in place of !! would allow a custom exception if a MyException class inheriting from Execption is declared.

Comments

0

You can use method lastIndexOf for getting the last occurrence of a value & indexOf for getting the first occurrence of a value from array.below is the code.

 fun main(args: Array<String>) {
     // Declaring array
     val arr = arrayOf("cat", "dog", "lion", "tiger", "dog", "rabbit")
     // for getting the last position of item
     println(arr.lastIndexOf("dog"))
    // for getting the first index of item
     println(arr.indexOf("dog"))
 }

1 Comment

Hello, please do not post duplicate (the accepted answer came first) or incomplete answers (your answer does not explain How can I throw an error when I search for something that is not in the array?). Always strive for high quality, take example from the accepted answer. Good luck!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.