Reading input from Command Line

suggest change

Input can be read from standard input (not from the args array). The example below reads two integers from one line. Destructuring requires exactly two tokens; otherwise it throws.

fun main(args: Array<String>) {

    println("Enter two numbers")
    var (a, b) = readLine()!!.split(' ') // !! asserts non-null and throws NullPointerException otherwise.

    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;

}

Enter two numbers to find the maximum. Output:

Enter two numbers
71 89

The value of b is 89
Max number is : 89

For the !! operator, see Null Safety.

Note: The example above compiles and runs in IntelliJ.

Feedback about page:

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



Table Of Contents