Search code examples
kotlinuser-inputsubroutine

Calling Subroutines in Kotlin


I can't seem to find any information on subroutines and how to call them in Kotlin. I'm practicing by creating a system which takes input from a user and displays the content prompting the user to say yes if their information is correct, or no if it is not. It then asks them to input "reset" to enter the subroutine until they enter yes.

The code has no errors, but when I get to the "reset" phase, the subroutine is never called and the program just hangs. It allows me to input something else but then just ends the program.

Here is the code below:

fun main(args: Array<String>) {
    println("Enter your name")
    val name = readLine()

    println("Enter your email")
    val email = readLine()

    println("Enter your location")
    val location = readLine()

    println("$name $location $email")
    println("Are you sure this is the correct information about you? Type yes or no.")
    val answer = readLine()

    if (answer == "yes") {
        println("Awesome. Details have been saved.")
        return
    } else if (answer == "no") {
        println("Type reset to retry")
        val reset = readLine()
        if (reset == "reset") {
            loop()
        }
    } else {
        println("Error has occurred")
    }
}

fun loop (){
    val answer = readLine()
    while(answer == "no"){
        println("Enter your name")
        val name = readLine()

        println("Enter your email")
        val email = readLine()

        println("Enter your location")
        val location = readLine()

        println("$name $location $email")
        println("Are you sure this is the correct information about you? Type yes or no.")
        if(answer != "yes"){
            println("Awesome. Details have been saved.")
            break
        }
    }
}

Solution

  • Do while loop can give the effect you want to achieve so try this -

    fun loop (){
        do {
            println("Enter your name")
            val name = readLine()
    
            println("Enter your email")
            val email = readLine()
    
            println("Enter your location")
            val location = readLine()
    
            println("$name $location $email")
            println("Are you sure this is the correct information about you? Type yes or no.")
            val answer = readLine()
    
            if(answer == "yes"){
                println("Awesome. Details have been saved.")
                break
            }
        }
        while(answer == "no")
    }