• Post Reply Bookmark Topic Watch Topic
  • New Topic

How to accept only integer value ?  RSS feed

 
Haring Jakobe
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Hi

My problem is user can enter numeric and strings. How can I limit that the program will only accepts integer values. Or much better if I can catch
the error that the user entered String value.


Im just new to java and trying to learn as much as possible. Many thanks.


Jakobe
 
Anu josh
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can either use Scanner.hasNextInt() or you can validate input using Integer.parseINt
 
Haring Jakobe
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Thanks for your advise.

My next question :
If the user entered "21ss" for example, my program gets error.
What's the best way to handle this situation?
 
Tim Cooke
Marshal
Posts: 3873
233
Clojure IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Are you familiar with Java Exceptions?
 
Campbell Ritchie
Marshal
Posts: 55793
164
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch

Please always tell us the full details about the error.
Also have a look at older posts in this forum. This is a discussion about a similar problem only a few weeks ago.

21ss is probably not a valid integer unless you have a radix > 28, so it is highly unlikely that you can match 21ss.
 
Campbell Ritchie
Marshal
Posts: 55793
164
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Anu josh wrote:You can either use Scanner.hasNextInt() or you can validate input using Integer.parseINt
The link I posted tells you why it is a bad idea to use parseInt. The hasNextInt method is much better, but there are problems with that, too, which are also discussed in the same link.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!