1

my question really just pertains to where I should put the bit of code that checks to make sure the input is a whole number. Thanks to anyone who helps.

public static String getQuantity(String aQuantity){
    while (isValidQuantity(aQuantity)== false ){
        errorMessage += "Enter Valid quantity\n";
    }
    return aQuantity;
    }
    private static boolean isValidQuantity(String aQuantity){
    boolean result = false;
    try{
        Double.parseDouble(aQuantity);
     //here?//
        result = true;
    }catch(Exception ex){
        result = false;
    }

    return result;
}
  • 1
    How about a simple regex? Provoking an `Exception` is definitly not an option and considered bad style. –  Feb 17 '16 at 01:54
  • 1
    You are already wrapping it in a try catch. parseDouble will throw and NumberFormatException. You can exit there or do something else like set a default. – essa Feb 17 '16 at 01:57
  • 1
    Regex is a best feature which can easily identify your string and validate the string.. Programs flow should be first validate the string against the regex and then try to parse it.. Advantage of this flow is no exception handling is needed while parsing it to the double or float what ever you want.. – Vikrant Kashyap Feb 17 '16 at 02:09
  • 1
    I'm going to say that lots of developers see it both ways. Performance wise regular expressions tend to be more expensive. I use them more for filtering rather than validation. You can [read a bit more here](http://stackoverflow.com/questions/5227633/regex-or-exception-handling) for lots of opinions.. I prefer to fail fast and cheap when it makes sense. – essa Feb 17 '16 at 02:34
  • @Paul. I apologize for my ignorance but what about this situation makes Exception a bad option? –  Feb 17 '16 at 05:58
  • 1
    @TheUnfortunateNudist `Exception`s should be exceptional (as already the name suggests), not a way of controlling the flow of a program. And throwing and afterwards catching an exception definitely costs more than setting up a simple check for an input with a valid format. –  Feb 17 '16 at 10:55
  • 1
    [Per the spec](http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-3.html#jvms-3.12) __Looking more closely, the **try block is compiled just as it would be if the try were not present**...If no exception is thrown... it behaves as though the try were not there.__ If your data is good more often than bad, try/catch is cheaper. User input is always more susceptible to being bad but the general case where you are dealing known data a regular expression is overkill IMO. Especially when you still have to create additional error handling if data doesn't match. Differing opinions :D – essa Feb 17 '16 at 13:43

2 Answers2

1

You can do it easily using regex. For double use this:

Pattern.compile("\\d+\\.\\d+")

If you want to take care of doubles in the scientific notations (e.g. like 3.4-e20), use this:

Pattern.compile("[-+]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?")

For whole number, you can simply use the parts before the . in each of the regex above. Like

Pattern.compile("\\d+")

For numbers that may have sign,

Pattern.compile("[-+]?[0-9]+")

Note the + at the end of the last one. There has to at least one digit for it to qualify as a number, hence you can not use *, which means zero or more occurrence.

Javadocs for regex here.

Test the double's pattern in regexr.

Sнаđошƒаӽ
  • 16,753
  • 12
  • 73
  • 90
0

Your solution should work, because any integer will parse as a double as well. You could make it more verbose, and have 0 represent invalid 1 represent an int and 2 represent a double.

private static int isValidQuantity(String aQuantity){
    int result = 0;
    //first try int
    try{
        Integer.parseInt(aQuantity);
        result = 1; //the parse worked
    }catch(NumberFormatException ex){
        result = 0;
    }

    if(result == 0)
    {
        //if it's not an int then try double
        try{
            Double.parseDouble(aQuantity);

            result = 2; //the parse worked
        }catch(NumberFormatException ex){
            result = 0;
        }
    }

    return result;
}
McAngus
  • 1,826
  • 18
  • 34