Stack Exchange network consists of 183 Q&A communities including Stack Overflow, the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.
One other (more general) method (though it is more of an anti-pattern in this particular case) to validate things is with a try/catch block. See this answer on Stack Overflowthis answer on Stack Overflow for an example on how to do this.
One other (more general) method (though it is more of an anti-pattern in this particular case) to validate things is with a try/catch block. See this answer on Stack Overflow for an example on how to do this.
One other (more general) method (though it is more of an anti-pattern in this particular case) to validate things is with a try/catch block. See this answer on Stack Overflow for an example on how to do this.
Enter 1st whole number:
> hello
Input must be a whole number. Try again:
> 5
Enter 2nd whole number:
> world
Input must be a whole number. Try again:
> 20
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
One other (more general) method (though it is more of an anti-pattern in this particular case) to validate things is with a try/catch block. See this answer on Stack Overflow for an example on how to do this.
###Formatting
One other (more general) method (though it is more of an anti-pattern in this particular case) to validate things is with a try/catch block. See this answer on Stack Overflow for an example on how to do this.
Result:
Enter 1st whole number:
> hello
Input must be a whole number. Try again:
> 5
Enter 2nd whole number:
> world
Input must be a whole number. Try again:
> 20
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
One other (more general) method (though it is more of an anti-pattern in this particular case) to validate things is with a try/catch block. See this answer on Stack Overflow for an example on how to do this.
A natural way to do this is with Scanner.hasNextInt(). Note that for this to work correctly, you will have to declare your variables outside of the try/catch block. Also, consider adding a little bit of feedback so it is less confusing for the user. Something like this, for example:
A natural way to do this is with Scanner.hasNextInt(). Note that for this to work correctly, you will have to declare your variables outside of the try/catch block. Also, consider adding a little bit of feedback so it is less confusing for the user. Something like this, for example:
A natural way to do this is with Scanner.hasNextInt(). Also, consider adding a little bit of feedback so it is less confusing for the user. Something like this, for example: