Results 1 to 3 of 3
Like Tree1Likes
  • 1 Post By Norm

Thread: How to determine if a String variable is a number?

  1. #1
    Join Date
    Jun 2016
    Posts
    7
    Rep Power
    0

    Question How to determine if a String variable is a number?

    For example, in my code I have a line that converts a String variable to an int variable.
    Java Code:
    String word = "4";
    int x = Integer.parseInt(word);
    // x will be set equal to 4
    If the String variable is not a number, it crashes the code.
    For error checking, I want to do the conversion only if the String variable is a number.
    How do I check if the String variable is a number?
    Java Code:
    if ( true ) {
    int x = Integer.parseInt(word);
    }
    else {
    // Display error message
    }

  2. #2
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    20,003
    Rep Power
    33

    Default Re: How to determine if a String variable is a number?

    How do I check if the String variable is a number?
    There are several ways:
    Wrap the call to the parseInt() method in a try catch block. If the String contains a non-int value, the parseInt method will throw an exception
    Use a regular expression to test the String's contents
    Put the String in the Scanner class's constructor and call hasNextInt() - if it returns false, the String does not contain an int. Note a space will stop scan
    Scan the String char by char and test if each is >= '0' and <= '9'
    Last edited by Norm; 07-03-2016 at 12:50 AM.
    If you don't understand my response, don't ignore it, ask a question.

  3. #3
    mmirbekian is offline Member
    Join Date
    Jul 2016
    Posts
    17
    Rep Power
    0

    Default Re: How to determine if a String variable is a number?

    Quote Originally Posted by Norm View Post
    There are several ways:
    Wrap the call to the parseInt() method in a try catch block. If the String contains a non-int value, the parseInt method will throw an exception
    Use a regular expression to test the String's contents
    Put the String in the Scanner class's constructor and call hasNextInt() - if it returns false, the String does not contain an int. Note a space will stop scan
    Scan the String char by char and test if each is >= '0' and <= '9'
    you mean: if(word.hasNextInt) ?

Similar Threads

  1. Replies: 2
    Last Post: 10-22-2015, 07:51 PM
  2. How To Determine Each Character When Written In A String?
    By JanAlbertLam in forum New To Java
    Replies: 6
    Last Post: 02-07-2013, 03:49 PM
  3. Replies: 1
    Last Post: 02-26-2012, 07:10 AM
  4. Replies: 2
    Last Post: 06-01-2010, 09:37 AM
  5. Replies: 10
    Last Post: 02-20-2010, 08:25 PM

Tags for this Thread

Posting Permissions

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