Reputation: 103
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])
}
Upvotes: 0
Views: 1615
Reputation: 9
val n1=Scanner(System.`in`)
println("Enter an number of input: ")
val n:Int=n1.nextInt()
val n3:ArrayList<Int> =ArrayList()
var i=0
for (i in 1..n){
print("enter an input of $i :")
val v=n1.nextInt()
n3.add(v)
}
println("the list is:$n3")
Upvotes: 0
Reputation: 518
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")
}
Upvotes: 2
Reputation: 109
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)
}
}
Upvotes: 1