Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

kotlin reject negative, string and float input

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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!")
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading