CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    Jul 1999
    Location
    India.
    Posts
    81

    how to test an integer?

    Hi,
    I have a textbox in html. I am using a post method in it. When the value is recieved by the servlet, I want to test whether the value recieved from the textbox is a number or not.

    Integer.parseInt(request.getParameter("textbex1"))
    would give an error if the user has not entered a valid number.

    Does anybody know the solution?
    I will be grateful for the solution

    Thanks in advance.
    Monika


  2. #2
    Join Date
    Mar 2000
    Location
    Dublin, Ireland
    Posts
    124

    Re: how to test an integer?

    Monika,

    You are correct in using the Integer.parseInt() method. To see if the String you passed it is a number, use the throw and catch exception handling for this method.

    In other words:
    // the integer
    int number = 0;
    // the string
    String theString = "Two";
    // the try block
    try {
    // parse the string and store in number
    number = Integer.parseInt(theString);
    }catch(java.lang.NumberFormatException e) {
    // this code is executed if there was an error parsing the String
    System.out.println("The String is not a number!");
    }


    Hope this helps!

    Regards,

    dogBear

    PS Please Rate this Response!!!!

  3. #3
    Join Date
    Jul 1999
    Location
    India.
    Posts
    81

    Re: how to test an integer?

    Hi,
    Thanks a lot for your reply.
    But I don't want to throw an exception. I just want to test if it is number or not. The solution could be in java or javascript.
    Bye,
    Monika


  4. #4
    Join Date
    Mar 2000
    Location
    Dublin, Ireland
    Posts
    124

    Re: how to test an integer?

    Monika,

    If you don't want to throw an exception, then simply test each character in the String, like so:

    // the String holding the text
    String theNumber = "25";
    // the sentinel
    boolean isANumber = true;
    // loop through each character in the String
    // notice that we're testing for two things:
    // 1) index remains in bounds
    // 2) isANumber remains true
    for ( int index = 0 ; index < theNumber.length() && isANumber ; index++ )
    if ( theNumber.charAt(index) < '0' || theNumber.charAt(index) > '9' )
    isANumber = false;

    // do the result printout...
    if ( isANumber )
    System.out.println("This is a number!");
    else
    System.out.println("This is NOT a number!");



    Is this more what you're looking for?

    Regards,

    dogBear

    PS Please Rate this Response!!!!

Posting Permissions

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





Click Here to Expand Forum to Full Width

Featured