Reading input from Command Line

suggest change

The arguments passed from the console can be received in the Kotlin program and it can be used as an input. You can pass N (1 2 3 and so on) numbers of arguments from the command prompt.

A simple example of a command-line argument in Kotlin.

fun main(args: Array<String>) {

    println("Enter Two number")
    var (a, b) = readLine()!!.split(' ') // !! this operator use for NPE(NullPointerException).

    println("Max number is : ${maxNum(a.toInt(), b.toInt())}")
}

fun maxNum(a: Int, b: Int): Int {

    var max = if (a > b) {
        println("The value of a is $a");
        a
    } else {
        println("The value of b is $b")
        b
    }

    return max;

}

Here, Enter two number from the command line to find the maximum number. Output :

Enter Two number
71 89 // Enter two number from command line

The value of b is 89
Max number is: 89

For !! Operator Please check Null Safety.

Note: Above example compile and run on Intellij.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents