Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 6 of 6

Thread: Confirming if a User Input is an Integer/Double

  1. #1
    Member
    Join Date
    Jun 2011
    Posts
    182
    My Mood
    Where
    Thanks
    15
    Thanked 8 Times in 8 Posts

    Default Confirming if a User Input is an Integer/Double

    I have been writing a simple calculator program (no GUI) and one thing I have noticed is that while the calculator is in a calculation mode (adding/subtracting/etc.), if the user inputs a word or some invalid symbol (usually characters), the program just throws an exception and ends.

    I fully understand why. The input line in the method is written as:
    [CODE]
    String userInput = user.getUserInput(" ");
    double addNum = Double.parseDouble(userInput);
    [/CODE]

    If I am correct, the JVM is trying to parse some input (say "cat") to a double and can't do that. So it throws the exception:
    Exception in thread "main" java.lang.NumberFormatException: For input string: "c
    at"
            at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:12
    22)
            at java.lang.Double.parseDouble(Double.java:510)
            at Arithmetic.Add(Arithmetic.java:5)
            at SimpleCalc.main(SimpleCalc.java:13)

    All I am looking to do is create an error guard that will detect if the user inputs a String that is not numeric and will say "Your input was invalid."

    I was thinking of using an IF statement to check if it was a integer/double but ran into two problems:

    1. I don't exactly know how to do that...
    2. The problem seems to occur when the parsing attempt is made on the input String. So the if statement would have to come before the parse. I'm not sure how to go about saying "All numeric strings"

    I have checked the API but I am rather new to Java so I don't understand all of it... forgive me if I missed something.

    Any help you can offer is appreciated. Thanks for your time!


  2. #2
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: Confirming if a User Input is an Integer/Double

    If I were you, I would just catch the Exception.

    You could also read it in as a String, then check to make sure it's a valid number.
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  3. The Following User Says Thank You to KevinWorkman For This Useful Post:

    bgroenks96 (June 7th, 2011)

  4. #3
    Forum old-timer
    Join Date
    Nov 2008
    Location
    Faversham, Kent, UK
    Posts
    472
    My Mood
    Mellow
    Thanks
    4
    Thanked 58 Times in 54 Posts

    Default Re: Confirming if a User Input is an Integer/Double

    As KevinWorkman says, the recommended way to deal with input that can't be processed ('exceptional' input) is to catch the exception and display your error message there. That's pretty much what Java exceptions are there for.

    The best way to use exceptions in your code is to try to keep the whole body of the method code within a single 'try' block, and catch any exceptions at the end of the method. It isn't always possible, but the idea is that you can write the body of your code without worrying serious errors, which makes the code simpler, clearer, and more robust. In cases where you need a 'catch' in the middle of the method code, it's worth considering putting the bit of code that may throw that exception into a separate method along with that catch... it's a judgement call - a question of deciding the best way to keep things clear and simple:
    void method(..) {
       // declare variables
       ...
       try {
          // body of method
          ...
       }
       // where possible, handle exceptions at end
       catch(Exception1 e1) {
          ...
       }
       catch(Exception2 e2) {
          ...
       }
    }

  5. The Following User Says Thank You to dlorde For This Useful Post:

    bgroenks96 (June 7th, 2011)

  6. #4
    Member
    Join Date
    Jun 2011
    Posts
    182
    My Mood
    Where
    Thanks
    15
    Thanked 8 Times in 8 Posts

    Default Re: Confirming if a User Input is an Integer/Double

    Quote Originally Posted by KevinWorkman View Post
    If I were you, I would just catch the Exception.

    You could also read it in as a String, then check to make sure it's a valid number.
    I like the catching idea.

    However, the class involves several methods (4 to be exact). Would it be possible to declare that all methods catch exceptions (I would rather not get into inheritance because the base format of this program doesn't really support it) or do I have to go through and add a try { and catch { to each method?

    EDIT: I successfully used the try and catch method to stop the exception from crashing the program. It now displays my error message. Thank you for your help!
    The question still stands, however, is it possible to declare a try/catch for all of the methods in a class?

    Thank you again for your help!
    Last edited by bgroenks96; June 7th, 2011 at 02:37 PM.

  7. #5
    Grand Poobah
    Join Date
    Mar 2011
    Posts
    1,545
    My Mood
    Grumpy
    Thanks
    0
    Thanked 167 Times in 158 Posts

    Default Re: Confirming if a User Input is an Integer/Double

    If I understand you correctly you can do this:
    public void boo {
        try {
            doo();
            foo();
            goo();
        } catch (Exception e) {
            // do something
        }
    }
     
    public void doo() throws Exception {
        //code
        // line that might throw exception
        //code
    }
     
    public void foo() throws Exception {
        //code
        // line that might throw exception
        //code
     
    }
     
    public void goo() throws Exception {
        //code
        // line that might throw exception
        //code
    }
    However, with variables it is recommended that you declare them in the smallest possible scope. You should do the same with try/catch statements. By that I mean if you have 20,000 lines of code and only one of them can throw an exception then put the try around that one line not the whole lot. So the above might be:
    public void boo {
        doo();
        foo();
        goo();
    }
     
    public void doo() {
        //code
        try {
            // line that might throw exception
        }
        //code
    }
     
    public void foo() {
        //code
        try {
            // line that might throw exception
        }
        //code
    }
     
    public void goo() {
        //code
        try {
            // line that might throw exception
        }
        //code
    }
    But it does depend upon the situation. It might make perfect sense for those methods to throw the exception back to the calling method, especially if you do not want the code after the exception to be executed.

    I remember when we first did any IO at Uni the first thing that the lecturer showed us was to add throws Exception to the main method. This was since we had not covered exceptions yet and we were just concentrating on IO. Now I would never do that. I will always handle the exception at the appropriate point in the code.

  8. #6
    Forum old-timer
    Join Date
    Nov 2008
    Location
    Faversham, Kent, UK
    Posts
    472
    My Mood
    Mellow
    Thanks
    4
    Thanked 58 Times in 54 Posts

    Default Re: Confirming if a User Input is an Integer/Double

    Quote Originally Posted by Junky View Post
    However, with variables it is recommended that you declare them in the smallest possible scope. You should do the same with try/catch statements. By that I mean if you have 20,000 lines of code and only one of them can throw an exception then put the try around that one line not the whole lot.
    Having said that, methods should be kept as short as possible (i.e. not 20,000 lines!), and a big advantage of exceptions is that they allow messy error handling to be removed from the body of the code, so in practice, you might want the try/catch to surround the block of code that might throw the exception, rather than the single line (I'm assuming the try/catch isn't being positioned just to indicate an exception-throwing call!). Of course, there are trivial exceptions (ha!) to the guideline, like using Thread.sleep(), where, in the absence of an interrupting thread, it's common to put the try..catch in the body of the code, because it's typically very small & self-contained, with a one-line try block and an empty or one liner catch. But I have seen even this put into a separate sleep() method (particularly when the sleep time is parameterized).

Similar Threads

  1. User Input File Name
    By PineAppleKing in forum Java Theory & Questions
    Replies: 12
    Last Post: June 3rd, 2011, 10:23 AM
  2. how to read an integer of DOUBLE datatype with type casting
    By amr in forum What's Wrong With My Code?
    Replies: 3
    Last Post: December 14th, 2010, 03:03 PM
  3. Typecasting of double variable to integer
    By JavaPF in forum Java Programming Tutorials
    Replies: 2
    Last Post: December 5th, 2010, 03:41 AM
  4. User Input Loop
    By cfmonster in forum Loops & Control Statements
    Replies: 7
    Last Post: August 24th, 2009, 01:52 PM
  5. How to check that console input should be integer only?
    By Konnor in forum File I/O & Other I/O Streams
    Replies: 3
    Last Post: February 2nd, 2009, 05:37 AM