test if a string is an integer?

Discussion in 'Java' started by dave, Jul 16, 2004.

  1. dave

    dave Guest

    I am reading input from a form. I want to validate the input by making sure
    that the string is actually an integer. How would I do this? Do i need to
    convert it to a character array and break down each character and test it?
    or is there an easier way? Thanks.


    ---
    Outgoing mail is certified Virus Free.
    Checked by AVG anti-virus system (http://www.grisoft.com).
    Version: 6.0.720 / Virus Database: 476 - Release Date: 7/14/04
     
    dave, Jul 16, 2004
    #1
    1. Advertising

  2. dave

    Murray Guest

    "dave" <> wrote in message
    news:FAHJc.59786$...
    > I am reading input from a form. I want to validate the input by making

    sure
    > that the string is actually an integer. How would I do this? Do i need to
    > convert it to a character array and break down each character and test it?
    > or is there an easier way? Thanks.
    >


    Try to perform Integer.parseInt(yourString) and if it throws a
    NumberFormatException you'll know the string isn't a valid integer
     
    Murray, Jul 16, 2004
    #2
    1. Advertising

  3. dave

    Roedy Green Guest

    On Fri, 16 Jul 2004 03:04:05 GMT, "dave"
    <> wrote or quoted :

    >I am reading input from a form. I want to validate the input by making sure
    >that the string is actually an integer.


    there is no such group as comp.lang.java.

    Just convert it and catch the exception if it is invalid.
    See http://mindprod.com/jgloss/converter.html

    --
    Canadian Mind Products, Roedy Green.
    Coaching, problem solving, economical contract programming.
    See http://mindprod.com/jgloss/jgloss.html for The Java Glossary.
     
    Roedy Green, Jul 16, 2004
    #3
  4. dave

    Murray Guest

    > there is no such group as comp.lang.java.

    I've heard several people mention this, yet comp.lang.java does seem to
    exist. Do you mean it's now defunct and should not be used?
     
    Murray, Jul 16, 2004
    #4
  5. "dave" <> wrote in message
    news:FAHJc.59786$...
    > I am reading input from a form. I want to validate the input by making

    sure
    > that the string is actually an integer. How would I do this? Do i need to
    > convert it to a character array and break down each character and test it?
    > or is there an easier way? Thanks.


    Hand the String to parseInt and catch NumberFormatException.
    see:
    http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Integer.html#parseInt(java.lang.String)
    --
    Gary
     
    Gary Labowitz, Jul 16, 2004
    #5
  6. "Roedy Green" <> wrote in message
    news:...
    >
    > there is no such group as comp.lang.java.
    >


    There is, its just not a 'core' group and hence not carried by all usenet
    servers.



    l8r, Mike N. Christoff
     
    Michael N. Christoff, Jul 16, 2004
    #6
  7. dave

    Liz Guest

    "Murray" <> wrote in message
    news:6PHJc.3087$...
    >
    > "dave" <> wrote in message
    > news:FAHJc.59786$...
    > > I am reading input from a form. I want to validate the input by making

    > sure
    > > that the string is actually an integer. How would I do this? Do i need

    to
    > > convert it to a character array and break down each character and test

    it?
    > > or is there an easier way? Thanks.
    > >

    >
    > Try to perform Integer.parseInt(yourString) and if it throws a
    > NumberFormatException you'll know the string isn't a valid integer
    >


    Do you really mean integer? Or is a "number" ok, then you can use
    Double.parseDouble(string); which will return a result for integers,
    floats, and doubles.
     
    Liz, Jul 16, 2004
    #7
  8. dave

    Chris Dutton Guest

    As an alternative to the solution already provided...

    import java.util.regex.*;

    ....

    Pattern integerPattern = Pattern.compile("^\d*$");
    Matcher matchesInteger = integerPattern.matcher(myString);
    boolean isInteger = matchesInteger.matches();

    or:

    boolean isInteger = Pattern.matches("^\d*$", myString);
     
    Chris Dutton, Jul 16, 2004
    #8
  9. dave

    Roedy Green Guest

    On Fri, 16 Jul 2004 03:24:57 GMT, "Murray"
    <> wrote or quoted :

    >I've heard several people mention this, yet comp.lang.java does seem to
    >exist. Do you mean it's now defunct and should not be used?


    see http://mindprod.com/jgloss/newsgroups.html


    It existed a decade or so ago.

    --
    Canadian Mind Products, Roedy Green.
    Coaching, problem solving, economical contract programming.
    See http://mindprod.com/jgloss/jgloss.html for The Java Glossary.
     
    Roedy Green, Jul 16, 2004
    #9
  10. dave

    Tony Morris Guest

    > I am reading input from a form. I want to validate the input by making
    sure
    > that the string is actually an integer. How would I do this? Do i need to
    > convert it to a character array and break down each character and test it?
    > or is there an easier way? Thanks.


    This question has been asked many times.
    You'll receive answers ranging from checking that each char is between '0'
    and '9' through to the use of regular expressions.
    All of these suggestions are severely flawed, offering no benefit, and in
    most cases creating a hindrance (i.e. not neutral side-effects).

    The reason that these suggestions are attempted is because nobody (assuming
    everybody knows what they are doing) likes catching a RuntimeException, and
    especially not for the purpose of control flow. There is no suitable
    alternative.

    If it really bothers you (as it does me), encapsulate the "brokenness" in a
    single method:

    public boolean isParsableToInt(String i)
    {
    try
    {
    Integer.parseInt(i);
    return true;
    }
    catch(NumberFormatException nfe)
    {
    return false;
    }
    }

    Note that there is a slight performance penalty for doing this - the only
    suitable alternative is to simply catch the RuntimeException each time an
    attempt to parse is made.

    --
    Tony Morris
    http://xdweb.net/~dibblego/
     
    Tony Morris, Jul 16, 2004
    #10
  11. "Michael N. Christoff" <> writes:

    > There is, its just not a 'core' group and hence not carried by all usenet
    > servers.


    It's a deprecated group, and therefore should not be "writable" by
    well-behaved news servers.
     
    Tor Iver Wilhelmsen, Jul 16, 2004
    #11
  12. Chris Dutton wrote:
    > As an alternative to the solution already provided...
    >
    > import java.util.regex.*;
    >
    > ...
    >
    > Pattern integerPattern = Pattern.compile("^\d*$");
    > Matcher matchesInteger = integerPattern.matcher(myString);
    > boolean isInteger = matchesInteger.matches();
    >
    > or:
    >
    > boolean isInteger = Pattern.matches("^\d*$", myString);


    Note that this method is *not* equivalent to the other methods which use
    Integer.parseInt(). This method will accept inputs that are outside the
    range of a Java int, while Integer.parseInt() will not. Use whichever
    one is appropriate for your application.

    Also, I believe you forgot about the negative sign. :)

    HTH,
    Ray

    --
    XML is the programmer's duct tape.
     
    Raymond DeCampo, Jul 16, 2004
    #12
  13. dave

    lordy Guest

    Raymond DeCampo <> wrote in
    news:sNPJc.46280$:

    > Chris Dutton wrote:
    >> As an alternative to the solution already provided...
    >>
    >> import java.util.regex.*;
    >>
    >> ...
    >>
    >> Pattern integerPattern = Pattern.compile("^\d*$");
    >> Matcher matchesInteger = integerPattern.matcher(myString);
    >> boolean isInteger = matchesInteger.matches();
    >>
    >> or:
    >>
    >> boolean isInteger = Pattern.matches("^\d*$", myString);

    >
    > Note that this method is *not* equivalent to the other methods which

    use
    > Integer.parseInt(). This method will accept inputs that are outside

    the
    > range of a Java int, while Integer.parseInt() will not. Use whichever
    > one is appropriate for your application.
    >
    > Also, I believe you forgot about the negative sign. :)
    >



    It will also match the empty string so is a good example why one shouldnt
    use tricks unless one is 37ETE HaX0r :)

    --
    Lordy
     
    lordy, Jul 16, 2004
    #13
  14. dave

    Chris Dutton Guest

    lordy wrote:

    > It will also match the empty string so is a good example why one shouldnt
    > use tricks unless one is 37ETE HaX0r :)


    Yeah yeah... I never said it was perfect, but it is an alternative.
    Maybe a pattern more like:

    ^-?\d+$
     
    Chris Dutton, Jul 17, 2004
    #14
  15. dave

    Tony Morris Guest

    "Chris Dutton" <> wrote in message
    news:Y3_Jc.44399$od7.18972@pd7tw3no...
    > lordy wrote:
    >
    > > It will also match the empty string so is a good example why one

    shouldnt
    > > use tricks unless one is 37ETE HaX0r :)

    >
    > Yeah yeah... I never said it was perfect, but it is an alternative.
    > Maybe a pattern more like:
    >
    > ^-?\d+$


    You will never achieve perfection with a regex, raising the question of "why
    bother?".
    After all, you will have to handle the cases that your regex misses (or the
    ones that it doesn't depending on your proposed hack) negating the whole
    purpose of attempting to check the validity of the data beforehand.

    Declare to catch the NumberFormatException.
    The Number subclasses *should* have had a 'isParsable' method or declared
    NumberFormatException to be checked - the best workaround to this
    unfortunate shortcoming of the core API is to explicitly catch the
    NumberFormatException. Sad, but true.

    --
    Tony Morris
    http://xdweb.net/~dibblego/
     
    Tony Morris, Jul 17, 2004
    #15
  16. dave

    Carl Howells Guest

    Tony Morris wrote:

    > You will never achieve perfection with a regex, raising the question of "why
    > bother?".


    Careful with that word "never". I could create a regex to recognize
    every legal decimal representation for a java int (32 bit, 2's
    complement, signed), fairly easily. After all.. There are only a
    finite number of possible values to check for.

    Not that I'd do by enumerating all of them, as a regex based on that
    would have at least 2^32 + 1 nodes in its internal automaton. But there
    are simpler approaches that would work in a decent amount of memory. I
    think I can get the version for the byte data type to at least be
    reasonable:

    ^(0*(1(2([0-7])|[01]\d)|\d{1,2}))|(-0*(1(2([0-8])|[01]\d)|\d{1,2}))$

    Note that for efficiency, all those () blocks should really be (?:)
    blocks, but that makes it much harder to read. This was actually
    tested, and actually works correctly.

    Anyway, clearly, doing the same thing for short, int, or long isn't
    harder, though the amount of typing does increase significantly. Doing
    something like that for floating-point types would be more difficult,
    but it's still obviously possible theoretically.

    Of course... All that's just my reaction to the word "never". I
    actually agree that regexes shouldn't be used to solve this kind of
    problem. To paraphrase the advice: "The programmer had a problem.
    Then he thought, 'Aha! I'll use a regex!' Then he had two problems."
     
    Carl Howells, Jul 17, 2004
    #16
  17. Tony Morris sez:
    >> I am reading input from a form. I want to validate the input by making

    > sure
    >> that the string is actually an integer. How would I do this? Do i need to
    >> convert it to a character array and break down each character and test it?
    >> or is there an easier way? Thanks.

    >
    > This question has been asked many times.
    > You'll receive answers ranging from checking that each char is between '0'
    > and '9' through to the use of regular expressions.
    > All of these suggestions are severely flawed, offering no benefit, and in
    > most cases creating a hindrance (i.e. not neutral side-effects).
    >
    > The reason that these suggestions are attempted is because nobody (assuming
    > everybody knows what they are doing) likes catching a RuntimeException, and
    > especially not for the purpose of control flow. There is no suitable
    > alternative.
    >
    > If it really bothers you (as it does me), encapsulate the "brokenness" in a
    > single method:
    >
    > public boolean isParsableToInt(String i)
    > {
    > try
    > {
    > Integer.parseInt(i);
    > return true;
    > }
    > catch(NumberFormatException nfe)
    > {
    > return false;
    > }
    > }
    >
    > Note that there is a slight performance penalty for doing this


    FVO "slight" heavily dependent on quality of the input: for
    input string that are mostly not valid Java ints the slowdown
    can be an order of magnitude, compared to the same number of
    input strings that are mostly valid Java ints. (Note that
    "integer" != "Java int": a number outside of 32-bit int range
    is still a perfectly good integer.)
    (It gets better when you get to floating-point numbers: last
    I checked Double.parseDouble() didn't understand "1e-3" or
    "+inf".)

    To sum it up: there are two ways:

    ..parseXXX() actually converts string to number and comes
    with exception overhead. You want to use it if you need to
    convert the strings. You don't want to use when parsing huge
    amounts of strings that are known to be mostly not Java
    numbers.

    Regexp and looking at the string character-by-character are
    the same method, the only difference is performance of
    regex match vs. that of your hand-rolled code. (And, of
    course, quality of your code/regexp.) It does not convert
    strings to numbers. It can recognize valid numbers that
    are not "Java valid numbers".

    Take your pick.

    Dima
    --
    True courage comes from steadying yourself and forcing yourself to ssh into the
    fscking thing yet again and not admitting that it doesn't care what it's done
    to your life. -- "Hidden among the nodes" by ADB
     
    Dimitri Maziuk, Jul 17, 2004
    #17
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. =?Utf-8?B?Sm9l?=

    CType(x,Integer) vs. Integer.Parse(x)

    =?Utf-8?B?Sm9l?=, Feb 6, 2006, in forum: ASP .Net
    Replies:
    7
    Views:
    5,976
    =?Utf-8?B?RGF2aWQgQW50b24=?=
    Feb 7, 2006
  2. =?ISO-8859-1?Q?Thomas_Gagn=E9?=

    No Math.min(Integer, Integer)?

    =?ISO-8859-1?Q?Thomas_Gagn=E9?=, Jul 29, 2003, in forum: Java
    Replies:
    0
    Views:
    535
    =?ISO-8859-1?Q?Thomas_Gagn=E9?=
    Jul 29, 2003
  3. Sebastian Stelzer

    How do I add an Integer to another Integer?

    Sebastian Stelzer, Oct 14, 2004, in forum: Java
    Replies:
    2
    Views:
    520
    Yu SONG
    Oct 15, 2004
  4. Skybuck Flying

    Call oddities: &Test() vs &Test vs Test

    Skybuck Flying, Oct 4, 2009, in forum: C Programming
    Replies:
    1
    Views:
    745
    Skybuck Flying
    Oct 4, 2009
  5. Randy Kramer
    Replies:
    12
    Views:
    396
    Robert Klemme
    Oct 25, 2007
Loading...

Share This Page