N
N
ngapp2020-09-08 00:39:13
Kotlin
ngapp, 2020-09-08 00:39:13

How to make the perfect input?

Hello everyone, let's suppose that you need to get the number a from the console from the user and check whether this number is greater than zero?
How to make it beautiful from without bulky designs?
The above variant only checks for Integer, but skips negative numbers.

print("Введите число A: ")
    val a = readLine()?.toIntOrNull() ?: print("Вы ввели не число\n")
    print("Вы ввели число: ${a}")


This design is compliant but not restrained
val n = readLine()?.toIntOrNull()
        ?.let { a ->
            if (a > 0) {
                println("Вы ввели число: ${a}")
            } else {
                println("Введенное число отрицательное\n")
            }
        }
        ?: println("Вы ввели не число\n")

Answer the question

In order to leave comments, you need to log in

2 answer(s)
T
Timur Pokrovsky, 2020-09-08
@hypnogaja

val a = readLine()?.toIntOrNull()?.takeIf { it > 0 }

println(if (a == null) "Вы ввели не число" else "Вы ввели число: $a" )

D
Dmtm, 2020-09-08
@Dmtm

print (readLine()?.toIntOrNull()?:0>0)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question