Question type thing for Integer

Discussion in 'Bukkit Discussion' started by PhantomUnicorns, Feb 18, 2017.

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

    PhantomUnicorns

    I was roaming the web of finding the most efficient way of testing if a String is an integer, and I found this:
    Code:
        public static boolean isInteger(String s) {
            try {
                Integer.parseInt(s);
            } catch (Exception e) {
                return false;
            }
            return true;
        }
    
    This is probably one of the worst ways you could do this,I found a bunch more but I want some input, anyone have a very efficient way?
     
  2. Offline

    AlvinB

    @PhantomUnicorns
    If you change catch (Exception e) to catch (NumberFormatException e) then you have actually got the best way to check it. It makes sure it can be made into an integer (in fact, it even does it). All other ways will always have some uncertainty.
     
  3. Offline

    PhantomUnicorns

    Well wait a sec let me make a quick method that is probably better:

    Code:
    public boolean isInteger(String string) {
      Char[] chars = string.toCharArray();
      for (int i = 0;i < string.length;i++) {
        if ((i == 0 && chars[i].matches("-")) || chars[i].matches("[^0-9]")) {
          return false;
        }
      }
    }
    
     
    Last edited: Feb 19, 2017
  4. Offline

    timtower Moderator Moderator

    @PhantomUnicorns Is it better or is it just different?
    What do you think that the implementation of Integer.parseInt() would be?
    And how about negative input?
     
  5. Offline

    PhantomUnicorns

    Well I don't know if it is better :p, sure I'll change it
     
Thread Status:
Not open for further replies.

Share This Page