Home > database >  How do I get user input in Kotlin to create a list?
How do I get user input in Kotlin to create a list?

Time:10-25

I'm trying to create a list of names from user input in the command line. This is what I have so far but obviously, it's not working. Anybody have any advice? Thanks!

fun main(args: Array<String>) { 
  
    print("write a list of names:")
    val listOfNames = readLine()
    print(listOfNames[1])


} 

CodePudding user response:

You need to initialize the list and have each name added to it in some sort of loop. Which also means you'd need some way for the user to break that loop.

Here's an example how you could do it:

fun main(args: Array<String>) {
    println("Write a list of names: (leave empty to quit)")
    val names: ArrayList<String> = ArrayList()

    while (true) {
        val enteredString = readLine()
        if (enteredString == "") break
        names.add(enteredString)
    }
}

CodePudding user response:

if you want a single line of input to be split into the list of names.. i assume you will split on space

val input: String = readLine()
val names: List<String> = input.split(' ')
names.forEachIndexed { index, name ->
    println("$index: $name")
}
  • Related