简体   繁体   中英

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

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])


} 

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)
    }
}

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")
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM