Skip to main content
replaced http://stackoverflow.com/ with https://stackoverflow.com/
Source Link

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.

added 289 characters in body
Source Link
Phrancis
  • 20.4k
  • 6
  • 68
  • 154

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.

###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.

###Formatting

deleted 110 characters in body
Source Link
Phrancis
  • 20.4k
  • 6
  • 68
  • 154

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:

added 704 characters in body
Source Link
Phrancis
  • 20.4k
  • 6
  • 68
  • 154
Loading
added 101 characters in body
Source Link
Phrancis
  • 20.4k
  • 6
  • 68
  • 154
Loading
Source Link
Phrancis
  • 20.4k
  • 6
  • 68
  • 154
Loading