[SOLVED] Check if part of a string is an integer?

Discussion in 'Plugin Development' started by EdTheLoon, Aug 11, 2011.

Thread Status:
Not open for further replies.
  1. Offline

    EdTheLoon

    So I have String args[] passed into one of my functions but sometimes a certain index in the array will be an integer. What is the best way to check that (for example) args[1] is an integer?
     
  2. Offline

    Zarius

    Don't know if there's an easier way but this should work:

    Code:
    Integer myInt = 0; // default value
    try {
        myInt = Integer.valueOf(myString);
    } catch(NumberFormatException x) {
        // assume it's not a number and do whatever you want
    }
    
     
  3. Offline

    avatarDr

    How can you declare myInt twice? And why?
     
  4. Offline

    Zarius

    Because I stuffed up :) My original code has the declaration inside the try/catch but I figured this might not be useful for the request above so I declared myInt outside the try/catch but forgot to remove the first declaration - fixed :D
     
  5. Offline

    avatarDr

    Is it difference between declaring in or out? Recenty I found that Eclipse compiler moves such expressions out of try{} automatically.
     
  6. Offline

    masteroftime

    When you declare something inside try it is not visible outside. Thats cause the code may not have been executed because of the exception.

    And you can also use a regex:

    Code:
    if(myString.match("\\d+"))
    {
    //it is an integer
    }
     
    EdTheLoon likes this.
  7. Offline

    Zarius

    @avatarDr

    Well, my original code was a little different:
    Code:
    String myConvertedString  = null;
    try {
        Integer myInt = Integer.valueOf(myString);
        myConvertedString = myInt.toString();
    } catch(NumberFormatException x) {
        // assume it's not a number and do whatever you want
    }
    
    Because I later needed to use the number as a string however if the original "myString" was not a number there's a lot of other code that runs. Hence my need to declare it inside - as masteroftime pointed out, if you declare it inside the try/catch then it's not visible outside the try/catch.
     
  8. Offline

    EdTheLoon

    That is just what I needed. Thank you very much.
     
Thread Status:
Not open for further replies.

Share This Page