plethorax
plethorax

Reputation: 149

Kotlin: Unable to find the element in the Arraylist<String>

My problem is bifurcated into: Is this the correct syntax of entering the elements in the Arraylist? Is there any other alternative? Unable to find the element from the given code.

var arylst= arrayListOf<String>()
println("enter the elements of arraylist")

for(index in 0..arylst.size-1) {
arylst[index] = readLine()!!
if (arylst.contains("Ritika"))
println("element found")
else  
println("not found")

Upvotes: 0

Views: 247

Answers (1)

FHTMitchell
FHTMitchell

Reputation: 12156

In order to enter elements into an ArrayList from user input, you need to do something like

val arrayList = arrayListOf<String>()
println("Enter elements of array list")

while (true) {  // see bellow
    arrayList.add(readLine()!!)
    if (condition()) { // choose what this does
        break
    }
}

println(arrayList) // see what it looks like

Now what that condition() is is up to you. It could be a fixed number of enteries, or stop when an entry meets some condition.


For example, keep adding enteries until enter is pressed with no entry

val arrayList = arrayListOf<String>()
println("Enter elements of array list (or nothing to stop entering)")

while (true) {
    val entry = readLine()!!
    if (entry.length == 0) {
        break
    } else {
        arrayList.add(entry)
    }
}

println(arrayList)

Upvotes: 1

Related Questions