Results 1 to 3 of 3
  1. #1
    Nanomech's Avatar
    Nanomech is offline Member
    Join Date
    Aug 2011
    Location
    England
    Posts
    71
    Rep Power
    0

    Default Easiest/Best way to achieve this

    Hi, I am doing a Math game so obviously I am asking the user to input numeric based information. I wanted to know the best way to prevent a program from crashing if the user enters anything other than digits. For example, if I enter "L", the program crashes. I believe it has something to do with the scanner using nextInt();

    Thank you in advance for any pointers you may have to prevent these errors. Would it be an if statement? Or something much more complicated?

    Thank you for your time.

    Regards,

    NM.
    [A!B]Java

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default Re: Easiest/Best way to achieve this

    Myself, I'd get the text as a String (if using a Scanner, then it's myScanner.nextLine()), and then parse the String to an int in a try/catch block, catching for a NumberFormatException. There are likely plenty of examples of this in this forum if you search. Start with the terms -- Scanner and NumberFormatException. Luck!

  3. #3
    Nanomech's Avatar
    Nanomech is offline Member
    Join Date
    Aug 2011
    Location
    England
    Posts
    71
    Rep Power
    0

    Default Re: Easiest/Best way to achieve this

    Thank you very much, I actually have a pdf version of a book and saw the try, catch example there. I weren't too sure if this was still used as the book was made in 2002. I'll have another look at that along with searching the forum.

    Thanks for the tip.

    Regards,

    NM.
    [A!B]Java

Similar Threads

  1. Replies: 0
    Last Post: 11-21-2011, 09:58 AM
  2. easiest ide to install
    By ishango in forum New To Java
    Replies: 5
    Last Post: 03-16-2011, 01:50 PM
  3. Easiest way to convert String to StringBuffer
    By unideal in forum New To Java
    Replies: 4
    Last Post: 12-13-2009, 01:43 PM
  4. Replies: 1
    Last Post: 08-13-2009, 09:10 PM
  5. [SOLVED] How to achieve this?
    By jazz2k8 in forum New To Java
    Replies: 14
    Last Post: 05-13-2008, 09:42 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •