0
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.

sangeetds
  • 390
  • 2
  • 12
  • 1
    The above is not compileable code, so it's not possible to tell what you're doing wrong in your actual code that you were able to run. `kotlin.Unit` is not an error code. It is what any function returns if it doesn't return anything useful. – Tenfour04 Jan 24 '22 at 02:59

1 Answers1

1

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))
}
Abby
  • 1,610
  • 3
  • 19
  • 35