Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

stopping program from crashing with incorrect data types  RSS feed

 
jon ninpoja
Ranch Hand
Posts: 291
3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hey guys

if i say have a menu
1) add
2) remove
3) exit

etc etc

and i have a scanner taking int in to work my menu

if you type letters instead...the program crashes

how can i fix this...is this where exceptions come in?

thanks
 
Norm Radder
Ranch Foreman
Posts: 2240
28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
if you type letters instead..

The Scanner class has methods for testing the type of data that has been entered.  Look at the API doc for the Scanner class for the methods with names that start with hasNext...  Use one of those to test what was entered.  If the input was not the correct type it could be read and ignored by using the next() method.
 
Campbell Ritchie
Marshal
Posts: 55717
163
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Search my posts for the names of some of those methods (especially if they end Int) and you will probably find something useful for your problem
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!