how can I validate if what a user types is an integer or not

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • kenrocks
    New Member
    • Oct 2008
    • 25

    how can I validate if what a user types is an integer or not

    my problem is to ensure that what the user types for the index of an array is really a digit and not a letter...please answer a.s.a.p. thx:D
  • JosAH
    Recognized Expert MVP
    • Mar 2007
    • 11453

    #2
    Have a look at the 'static int parseInt(String s) throws NumberFormatExc eption'
    method in the Integer class. It throws an exception when the String doesn't
    represent a valid int value.

    kind regards,

    Jos

    Comment

    • kenrocks
      New Member
      • Oct 2008
      • 25

      #3
      In regard with your answer...how ill I know if the user typed a string value if it automatically converts it into an integer? Well the result I want to get is not an exception I just want to place the values in an if statement and if that statement states that they are not of equal data type...it will display a .setText message that I will indicate...

      Comment

      • JosAH
        Recognized Expert MVP
        • Mar 2007
        • 11453

        #4
        Originally posted by kenrocks
        Well the result I want to get is not an exception I just want to place the values in an if statement and if that statement states that they are not of equal data type...it will display a .setText message that I will indicate...
        Of course you have to catch that mentioned exception and take the appropriate
        action(s). The method does its part, you do the other part.

        kind regards,

        Jos

        Comment

        • kenrocks
          New Member
          • Oct 2008
          • 25

          #5
          So I have to try and catch? Can u teach me the basics of that methods

          Comment

          • JosAH
            Recognized Expert MVP
            • Mar 2007
            • 11453

            #6
            Originally posted by kenrocks
            So I have to try and catch? Can u teach me the basics of that methods
            Simply wrap that method call in a try ... catch block; if the 'try' part completes
            succesfully your String represented a number; if the 'catch' clause is executed
            your String didn't represent a valid int number; it's some sort of an if-else structure. Look:

            Code:
            String s= // your String value
            int value; // the result of the method
            try {
               value= Integer.parse(s);
               // here the String represented an int
            }
            catch (NumberFormatException nfe) {
               // here the String didn't represent an int
            }
            kind regards,

            Jos

            Comment

            Working...