dimanche 5 août 2018

Other way for validating user input rather than throws exception

I want the user to input a number wherein it will display a message if the number is positive or negative. The code is working fine with this logic using an if and else statement

int num = kb.nextInt();

if (num >= 0)
//positive number
else
//negative number

Now what I want to do is for the code to show an error message if the user inputs a string number. I know several ways for this do it in a catch method or something, but I want it to be able to achieve in an if else statement like this.

if (num >= 0)
//positive number
else if (num < 0)
//negative number
else
//invalid user input

However, the code above does not work. It i enter 0 and above it will display positive if it is below 0 it will display negative but if i input not an integer then it will display Exception in main thread ....

How can this be achievable using simple codes? and why wont this code work when in php, it will?

Aucun commentaire:

Enregistrer un commentaire