Home > OS >  kotlin reject negative, string and float input
kotlin reject negative, string and float input

Time:02-18

I'm not allowed to change the toIntOrNull() and I need to reject every string, float, and negative input. I tried to do it with n is String but I just encountered and error. Is there any other way to do it?

Here's my code:

fun main(){
    print("Enter number of numbers from Fibonacci: ")
    var n: Int? = readLine()?.toIntOrNull()
    
    //print("Input is Invalid!")
    var total = fib(n)
    print("Total $total")
}

An example of what should appear when a string, double or negative is entered:

Enter number of numbers from Fibonacci: one
Input is Invalid!

CodePudding user response:

print("Enter number of numbers from Fibonacci: ")
var n: Int? = readLine()?.toIntOrNull()

if (n != null && n >= 0) {
  // if n is not null, then n is an Int (because of toIntOrNull() above)
  val total = fib(n!!)
  print("Total $total")
} else {
  print("Input is Invalid!")
}
  • Related