I'm trying to take names and the amount of groups from a user. Then separate them into groups. Kotlin

47 Views Asked by At
fun main(args: Array<String>) {
    
    //receive names from user
    print("Enter the names: ")
    val names = readLine()?.split("/n")

    //receive number of groups from the user
    print("Enter number of groups: ")
    val group = readLine()

    print(names.chunked(group))
}

I was trying to print the users into evenly separated groups. I found that I could use chunked to accomplish this. But when I try to input the amount of groups to the chunked function nothing happens. it outputs "kotlin.Unit" I'm guessing this is an error code. But I don't know how I messed up my code.

1

There are 1 best solutions below

0
Abby On

As mentioned in the comments, this code does not compile. It still has the following problems:

  1. names can be null, so you'll either have to ensure that it isn't, which you could do using the Elvis operator:

    val names = readLine()?.split("\n") ?: return
    

    Or you can use a safe call on names wherever you use it:

    names?.chunked(group)
    
  2. If you look at the documentation for chunked, you'll see that it has one parameter, size of type Int. However, you are passing a String to it, which you've read from the user. You'll have to try to convert this string to an int before passing it into chunked:

    val group = readLine()?.trim()?.split(" ")?.first()?.toInt() ?: return
    

    Note that I'm trimming and splitting the user input to increase chances of retrieving a valid int.

Fixing these problems makes your code compile. However, there's one more thing to fix. Assuming you meant the newline character with /n, you are now using the newline character as a separator for the names as well as to indicate that the user is done entering names. I suggest you use something different, like a comma. In total, this could give something like the following.

fun main() {
    //receive names from user
    print("Enter the names (separated by a comma): ")
    val names = readLine()?.split(",")?.map { it.trim() }

    //receive number of groups from the user
    print("Enter number of groups: ")
    val group = readLine()?.trim()?.split(" ")?.firstOrNull()?.toInt() ?: return

    print(names?.chunked(group))
}