• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Preventing program from crashing when user enters a char instead of a numerical input

 
Jay Dobrzyn
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi!
Am very new at java (only been doing if, while and so on. No idea of arrays, bufferstrings etc! Presently using consolewindow for input) and my problem is this:
Basically, when I ask the user for a int or a double input and he/she enters a char, then the whole thing hangs; ideally, if the user does that, I'd like the question to be repeated.
eg: c.out.println("Please enter number needed") ;
num = c.input.readInt () ;
I've been able to block sort the other way round, in that the program will loop back to the question should the user enter an int instead of a char by:
if (!(word == 'h') || word == 'r')
and then putting another c.out.println and readString etc underneath.
For my problem I've tried doing whiles and ifs based on (!(num >= 0) %% num <= 0) but within a while statement, all I get is a just a mess!
Is there a simple way to solve this using whiles and ifs?
Thanks!
Robin
[ March 19, 2004: Message edited by: Jay Dobrzyn ]
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Look into try & catch with something like:

If try/catch is new to you, look up exceptions in a good book. Bruce Eckell's Thinking In Java is free online: http://64.78.49.204/
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic