Jaki jest najlepszy sposób na sprawdzenie, czy łańcuch znaków reprezentuje liczbę całkowitą w Javie?

Zwykle używam poniższego idiomu, aby sprawdzić, czy łańcuch można przekonwertować na liczbę całkowitą.

public boolean isInteger( String input ) {
    try {
        Integer.parseInt( input );
        return true;
    }
    catch( Exception e ) {
        return false;
    }
}
Czy to tylko ja, czy to wydaje się trochę hakerskie? Co jest lepszym sposobem?

Zobacz moją odpowiedź (z benchmarkami, w oparciu o wcześniejszą odpowiedź przez CodingWithSpike ), aby zobaczyć, dlaczego odwróciłem swoje stanowisko i zaakceptowałem odpowiedź Jonasa Klemminga na ten problem. Myślę, że ten oryginalny kod będzie używany przez większość ludzi, ponieważ jest szybszy zaimplementować, i bardziej konserwowalne, ale to rzędy wielkości wolniej, gdy dane nie-integer są dostarczane.

Author: user1803551, 2008-10-25

30 answers

Jeśli nie jesteś zaniepokojony potencjalnymi problemami z przepełnieniem, ta funkcja będzie działać około 20-30 razy szybciej niż przy użyciu Integer.parseInt().

public static boolean isInteger(String str) {
    if (str == null) {
        return false;
    }
    int length = str.length();
    if (length == 0) {
        return false;
    }
    int i = 0;
    if (str.charAt(0) == '-') {
        if (length == 1) {
            return false;
        }
        i = 1;
    }
    for (; i < length; i++) {
        char c = str.charAt(i);
        if (c < '0' || c > '9') {
            return false;
        }
    }
    return true;
}
 179
Author: Jonas K,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-04-12 21:46:41

Masz to, ale powinieneś tylko złapać NumberFormatException.

 64
Author: Ovidiu Pacurar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-11-12 09:17:45

Zrobiłem szybki benchmark. Wyjątki nie są w rzeczywistości tak kosztowne, chyba że zaczniesz wyskakiwać z powrotem wiele metod i JVM musi zrobić dużo pracy, aby uzyskać stos realizacji w miejscu. Pozostając w tej samej metodzie, nie są złymi wykonawcami.

 public void RunTests()
 {
     String str = "1234567890";

     long startTime = System.currentTimeMillis();
     for(int i = 0; i < 100000; i++)
         IsInt_ByException(str);
     long endTime = System.currentTimeMillis();
     System.out.print("ByException: ");
     System.out.println(endTime - startTime);

     startTime = System.currentTimeMillis();
     for(int i = 0; i < 100000; i++)
         IsInt_ByRegex(str);
     endTime = System.currentTimeMillis();
     System.out.print("ByRegex: ");
     System.out.println(endTime - startTime);

     startTime = System.currentTimeMillis();
     for(int i = 0; i < 100000; i++)
         IsInt_ByJonas(str);
     endTime = System.currentTimeMillis();
     System.out.print("ByJonas: ");
     System.out.println(endTime - startTime);
 }

 private boolean IsInt_ByException(String str)
 {
     try
     {
         Integer.parseInt(str);
         return true;
     }
     catch(NumberFormatException nfe)
     {
         return false;
     }
 }

 private boolean IsInt_ByRegex(String str)
 {
     return str.matches("^-?\\d+$");
 }

 public boolean IsInt_ByJonas(String str)
 {
     if (str == null) {
             return false;
     }
     int length = str.length();
     if (length == 0) {
             return false;
     }
     int i = 0;
     if (str.charAt(0) == '-') {
             if (length == 1) {
                     return false;
             }
             i = 1;
     }
     for (; i < length; i++) {
             char c = str.charAt(i);
             if (c <= '/' || c >= ':') {
                     return false;
             }
     }
     return true;
 }

Wyjście:

ByException: 31

ByRegex: 453 (Uwaga: ponowne kompilowanie wzorca za każdym razem)

ByJonas: 16

Zgadzam się, że rozwiązanie Jonasa K jest najbardziej wytrzymałe. Wygląd jakby wygrał :)
 40
Author: CodingWithSpike,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-11-30 06:49:21

Ponieważ istnieje możliwość, że ludzie nadal odwiedzają tutaj i będą stronniczy wobec Regex po benchmarkach... Więc zamierzam dać zaktualizowaną wersję benchmarka, ze skompilowaną wersją Regex. Który w przeciwieństwie do poprzednich benchmarków, ten pokazuje rozwiązanie Regex rzeczywiście ma konsekwentnie dobrą wydajność.

Skopiowany z Bill Jaszczur i zaktualizowany o skompilowaną wersję:

private final Pattern pattern = Pattern.compile("^-?\\d+$");

public void runTests() {
    String big_int = "1234567890";
    String non_int = "1234XY7890";

    long startTime = System.currentTimeMillis();
    for(int i = 0; i < 100000; i++)
            IsInt_ByException(big_int);
    long endTime = System.currentTimeMillis();
    System.out.print("ByException - integer data: ");
    System.out.println(endTime - startTime);

    startTime = System.currentTimeMillis();
    for(int i = 0; i < 100000; i++)
            IsInt_ByException(non_int);
    endTime = System.currentTimeMillis();
    System.out.print("ByException - non-integer data: ");
    System.out.println(endTime - startTime);

    startTime = System.currentTimeMillis();
    for(int i = 0; i < 100000; i++)
            IsInt_ByRegex(big_int);
    endTime = System.currentTimeMillis();
    System.out.print("\nByRegex - integer data: ");
    System.out.println(endTime - startTime);

    startTime = System.currentTimeMillis();
    for(int i = 0; i < 100000; i++)
            IsInt_ByRegex(non_int);
    endTime = System.currentTimeMillis();
    System.out.print("ByRegex - non-integer data: ");
    System.out.println(endTime - startTime);

    startTime = System.currentTimeMillis();
    for (int i = 0; i < 100000; i++)
            IsInt_ByCompiledRegex(big_int);
    endTime = System.currentTimeMillis();
    System.out.print("\nByCompiledRegex - integer data: ");
    System.out.println(endTime - startTime);

    startTime = System.currentTimeMillis();
    for (int i = 0; i < 100000; i++)
            IsInt_ByCompiledRegex(non_int);
    endTime = System.currentTimeMillis();
    System.out.print("ByCompiledRegex - non-integer data: ");
    System.out.println(endTime - startTime);


    startTime = System.currentTimeMillis();
    for(int i = 0; i < 100000; i++)
            IsInt_ByJonas(big_int);
    endTime = System.currentTimeMillis();
    System.out.print("\nByJonas - integer data: ");
    System.out.println(endTime - startTime);

    startTime = System.currentTimeMillis();
    for(int i = 0; i < 100000; i++)
            IsInt_ByJonas(non_int);
    endTime = System.currentTimeMillis();
    System.out.print("ByJonas - non-integer data: ");
    System.out.println(endTime - startTime);
}

private boolean IsInt_ByException(String str)
{
    try
    {
        Integer.parseInt(str);
        return true;
    }
    catch(NumberFormatException nfe)
    {
        return false;
    }
}

private boolean IsInt_ByRegex(String str)
{
    return str.matches("^-?\\d+$");
}

private boolean IsInt_ByCompiledRegex(String str) {
    return pattern.matcher(str).find();
}

public boolean IsInt_ByJonas(String str)
{
    if (str == null) {
            return false;
    }
    int length = str.length();
    if (length == 0) {
            return false;
    }
    int i = 0;
    if (str.charAt(0) == '-') {
            if (length == 1) {
                    return false;
            }
            i = 1;
    }
    for (; i < length; i++) {
            char c = str.charAt(i);
            if (c <= '/' || c >= ':') {
                    return false;
            }
    }
    return true;
}

Wyniki:

ByException - integer data: 45
ByException - non-integer data: 465

ByRegex - integer data: 272
ByRegex - non-integer data: 131

ByCompiledRegex - integer data: 45
ByCompiledRegex - non-integer data: 26

ByJonas - integer data: 8
ByJonas - non-integer data: 2
 37
Author: Felipe,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-10-17 14:08:31
org.apache.commons.lang.StringUtils.isNumeric 

Chociaż standardowa biblioteka Javy naprawdę tęskni za takimi funkcjami narzędziowymi

Myślę, że Apache Commons jest "must have" dla każdego programisty Javy

Szkoda, że nie jest jeszcze przeportowany do Java5

 35
Author: Łukasz Bownik,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2008-10-27 10:03:38

To częściowo zależy od tego, co masz na myśli przez "Można przekonwertować na liczbę całkowitą".

Jeśli masz na myśli "można przekształcić w int w Javie" to odpowiedź Jonasa jest dobrym początkiem, ale nie do końca kończy pracę. To przejdzie 9999999999999999999999999999999 na przykład. Dodałbym normalne połączenie try/catch z własnego pytania na końcu metody.

Sprawdzanie znak po znaku skutecznie odrzuci przypadki" not an integer at all", pozostawiając " it ' s an integer but Java can 't handle it" przypadki, które mają być przechwycone przez wolniejszą trasę wyjątku. Ty mógłbyś zrobić to również ręcznie, ale byłoby to dużo bardziej skomplikowane.

 23
Author: Jon Skeet,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2008-10-26 07:26:01

Tylko jeden komentarz o regexp. Każdy podany tutaj przykład jest błędny!. Jeśli chcesz użyć wyrażenia regularnego, nie zapomnij, że kompilacja wzoru zajmuje dużo czasu. To:

str.matches("^-?\\d+$")

I jeszcze to:

Pattern.matches("-?\\d+", input);

Powoduje kompilację wzorca w każdym wywołaniu metody. Aby użyć go poprawnie wykonaj:

import java.util.regex.Pattern;

/**
 * @author Rastislav Komara
 */
public class NaturalNumberChecker {
    public static final Pattern PATTERN = Pattern.compile("^\\d+$");

    boolean isNaturalNumber(CharSequence input) {
        return input != null && PATTERN.matcher(input).matches();
    }
}
 19
Author: Rastislav Komara,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-06-14 11:27:46

Istnieje wersja guava:

import com.google.common.primitives.Ints;

Integer intValue = Ints.tryParse(stringValue);

Zwróci null zamiast rzucać wyjątek, jeśli nie przetworzy ciągu.

 13
Author: abalcerek,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-01-23 09:10:41

Skopiowałem kod z rally25rs answer i dodałem kilka testów dla danych nie-integer. Wyniki są niezaprzeczalnie na korzyść metody opublikowanej przez Jonasa Klemminga. Wyniki dla metody wyjątków, które pierwotnie opublikowane są całkiem dobre, gdy masz dane całkowite, ale są najgorsze, gdy nie, podczas gdy wyniki dla rozwiązania RegEx (że założę się, że wiele osób używa) były konsekwentnie złe. Zobacz odpowiedź Felipe dla skompilowanego przykładu regex, który jest znacznie szybciej.

public void runTests()
{
    String big_int = "1234567890";
    String non_int = "1234XY7890";

    long startTime = System.currentTimeMillis();
    for(int i = 0; i < 100000; i++)
        IsInt_ByException(big_int);
    long endTime = System.currentTimeMillis();
    System.out.print("ByException - integer data: ");
    System.out.println(endTime - startTime);

    startTime = System.currentTimeMillis();
    for(int i = 0; i < 100000; i++)
        IsInt_ByException(non_int);
    endTime = System.currentTimeMillis();
    System.out.print("ByException - non-integer data: ");
    System.out.println(endTime - startTime);

    startTime = System.currentTimeMillis();
    for(int i = 0; i < 100000; i++)
        IsInt_ByRegex(big_int);
    endTime = System.currentTimeMillis();
    System.out.print("\nByRegex - integer data: ");
    System.out.println(endTime - startTime);

    startTime = System.currentTimeMillis();
    for(int i = 0; i < 100000; i++)
        IsInt_ByRegex(non_int);
    endTime = System.currentTimeMillis();
    System.out.print("ByRegex - non-integer data: ");
    System.out.println(endTime - startTime);

    startTime = System.currentTimeMillis();
    for(int i = 0; i < 100000; i++)
        IsInt_ByJonas(big_int);
    endTime = System.currentTimeMillis();
    System.out.print("\nByJonas - integer data: ");
    System.out.println(endTime - startTime);

    startTime = System.currentTimeMillis();
    for(int i = 0; i < 100000; i++)
        IsInt_ByJonas(non_int);
    endTime = System.currentTimeMillis();
    System.out.print("ByJonas - non-integer data: ");
    System.out.println(endTime - startTime);
}

private boolean IsInt_ByException(String str)
{
    try
    {
        Integer.parseInt(str);
        return true;
    }
    catch(NumberFormatException nfe)
    {
        return false;
    }
}

private boolean IsInt_ByRegex(String str)
{
    return str.matches("^-?\\d+$");
}

public boolean IsInt_ByJonas(String str)
{
    if (str == null) {
            return false;
    }
    int length = str.length();
    if (length == 0) {
            return false;
    }
    int i = 0;
    if (str.charAt(0) == '-') {
            if (length == 1) {
                    return false;
            }
            i = 1;
    }
    for (; i < length; i++) {
            char c = str.charAt(i);
            if (c <= '/' || c >= ':') {
                    return false;
            }
    }
    return true;
}

Wyniki:

ByException - integer data: 47
ByException - non-integer data: 547

ByRegex - integer data: 390
ByRegex - non-integer data: 313

ByJonas - integer data: 0
ByJonas - non-integer data: 16
 12
Author: Bill the Lizard,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 11:47:17

To jest krótsze, ale krótsze niekoniecznie jest lepsze (i nie wychwytuje wartości całkowite, które są poza zakresem, Jak wskazano w komentarzu danatela):

input.matches("^-?\\d+$");

Osobiscie, poniewaz implementacja jest w metodzie helper i poprawnosc przebija Dlugosc, ja po prostu wybralbym cos takiego jak to co masz (minus zlapanie klasy bazowej Exception a nie NumberFormatException).

 6
Author: Jonny Buchanan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 11:55:06

Możesz użyć metody matches klasy string. [0-9] przedstawia wszystkie możliwe wartości, + oznacza, że musi mieć co najmniej jeden znak, a * oznacza, że może mieć zero lub więcej znaków.

boolean isNumeric = yourString.matches("[0-9]+"); // 1 or more characters long, numbers only
boolean isNumeric = yourString.matches("[0-9]*"); // 0 or more characters long, numbers only
 6
Author: Kaitie,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-12-13 21:41:50

A może:

return Pattern.matches("-?\\d+", input);
 4
Author: Kristian,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2008-10-25 23:12:13

To jest Java 8 wariacja Jonasa Klemminga odpowiedź:

public static boolean isInteger(String str) {
    return str != null && str.length() > 0 &&
         IntStream.range(0, str.length()).allMatch(i -> i == 0 && (str.charAt(i) == '-' || str.charAt(i) == '+')
                  || Character.isDigit(str.charAt(i)));
}

Kod badania:

public static void main(String[] args) throws NoSuchAlgorithmException, UnsupportedEncodingException {
    Arrays.asList("1231231", "-1232312312", "+12313123131", "qwqe123123211", "2", "0000000001111", "", "123-", "++123",
            "123-23", null, "+-123").forEach(s -> {
        System.out.printf("%15s %s%n", s, isInteger(s));
    });
}

Wyniki kodu testu:

        1231231 true
    -1232312312 true
   +12313123131 true
  qwqe123123211 false
              2 true
  0000000001111 true
                false
           123- false
          ++123 false
         123-23 false
           null false
          +-123 false
 4
Author: gil.fernandes,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-03-23 19:54:18

Wystarczy sprawdzić NumberFormatException:-

 String value="123";
 try  
 {  
    int s=Integer.parseInt(any_int_val);
    // do something when integer values comes 
 }  
 catch(NumberFormatException nfe)  
 {  
          // do something when string values comes 
 }  
 3
Author: duggu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-07-26 06:12:10

Jeśli tablica łańcuchów zawiera czyste liczby całkowite i ciągi znaków, poniższy kod powinien działać. Wystarczy spojrzeć na pierwszą postać. np. ["4","44","abc","77","bond"]

if (Character.isDigit(string.charAt(0))) {
    //Do something with int
}
 3
Author: realPK,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-03-18 02:19:39

Możesz również użyć klasy Scanner i użyć hasNextInt () - i to pozwala na testowanie również innych typów, np. pływaków itp.

 3
Author: Matthew Schinckel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-04-06 18:19:33

Jeśli chcesz sprawdzić, czy łańcuch reprezentuje liczbę całkowitą, która pasuje do typu int, zrobiłem małą modyfikację odpowiedzi Jonasa, tak, że ciągi, które reprezentują liczby całkowite większe niż liczba całkowita.MAX_VALUE lub mniejszy niż liczba całkowita.MIN_VALUE, zwróci teraz false. Na przykład: "3147483647" zwróci false, ponieważ 3147483647 jest większy niż 2147483647, a także "-2147483649" zwróci false, ponieważ -2147483649 jest mniejszy niż -2147483648.

public static boolean isInt(String s) {
  if(s == null) {
    return false;
  }
  s = s.trim(); //Don't get tricked by whitespaces.
  int len = s.length();
  if(len == 0) {
    return false;
  }
  //The bottom limit of an int is -2147483648 which is 11 chars long.
  //[note that the upper limit (2147483647) is only 10 chars long]
  //Thus any string with more than 11 chars, even if represents a valid integer, 
  //it won't fit in an int.
  if(len > 11) {
    return false;
  }
  char c = s.charAt(0);
  int i = 0;
  //I don't mind the plus sign, so "+13" will return true.
  if(c == '-' || c == '+') {
    //A single "+" or "-" is not a valid integer.
    if(len == 1) {
      return false;
    }
    i = 1;
  }
  //Check if all chars are digits
  for(; i < len; i++) {
    c = s.charAt(i);
    if(c < '0' || c > '9') {
      return false;
    }
  }
  //If we reached this point then we know for sure that the string has at
  //most 11 chars and that they're all digits (the first one might be a '+'
  // or '-' thought).
  //Now we just need to check, for 10 and 11 chars long strings, if the numbers
  //represented by the them don't surpass the limits.
  c = s.charAt(0);
  char l;
  String limit;
  if(len == 10 && c != '-' && c != '+') {
    limit = "2147483647";
    //Now we are going to compare each char of the string with the char in
    //the limit string that has the same index, so if the string is "ABC" and
    //the limit string is "DEF" then we are gonna compare A to D, B to E and so on.
    //c is the current string's char and l is the corresponding limit's char
    //Note that the loop only continues if c == l. Now imagine that our string
    //is "2150000000", 2 == 2 (next), 1 == 1 (next), 5 > 4 as you can see,
    //because 5 > 4 we can guarantee that the string will represent a bigger integer.
    //Similarly, if our string was "2139999999", when we find out that 3 < 4,
    //we can also guarantee that the integer represented will fit in an int.
    for(i = 0; i < len; i++) {
      c = s.charAt(i);
      l = limit.charAt(i);
      if(c > l) {
        return false;
      }
      if(c < l) {
        return true;
      }
    }
  }
  c = s.charAt(0);
  if(len == 11) {
    //If the first char is neither '+' nor '-' then 11 digits represent a 
    //bigger integer than 2147483647 (10 digits).
    if(c != '+' && c != '-') {
      return false;
    }
    limit = (c == '-') ? "-2147483648" : "+2147483647";
    //Here we're applying the same logic that we applied in the previous case
    //ignoring the first char.
    for(i = 1; i < len; i++) {
      c = s.charAt(i);
      l = limit.charAt(i);
      if(c > l) {
        return false;
      }
      if(c < l) {
        return true;
      }
    }
  }
  //The string passed all tests, so it must represent a number that fits
  //in an int...
  return true;
}
 2
Author: ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-08-26 18:35:34

Możesz spróbować Apache utils

NumberUtils.isCreatable(myText)

Zobacz javadoc tutaj

 2
Author: borjab,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-06-19 12:22:59

Prawdopodobnie musisz również wziąć pod uwagę przypadek użycia:

Jeśli przez większość czasu spodziewasz się, że liczby są poprawne, przechwycenie wyjątku powoduje tylko obciążenie wydajności podczas próby konwersji nieprawidłowych liczb. Podczas gdy wywołanie jakiejś metody isInteger(), a następnie konwersja za pomocą Integer.parseInt() spowoduje Zawsze wywołanie narzutu wydajności dla poprawnych liczb - łańcuchy są przetwarzane dwa razy, raz przez sprawdzenie i raz przez konwersję.

 1
Author: mobra66,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-05-02 08:33:41

Jest to modyfikacja kodu Jonas ', który sprawdza, czy łańcuch jest w zakresie, który ma być wrzucony do liczby całkowitej.

public static boolean isInteger(String str) {
    if (str == null) {
        return false;
    }
    int length = str.length();
    int i = 0;

    // set the length and value for highest positive int or lowest negative int
    int maxlength = 10;
    String maxnum = String.valueOf(Integer.MAX_VALUE);
    if (str.charAt(0) == '-') { 
        maxlength = 11;
        i = 1;
        maxnum = String.valueOf(Integer.MIN_VALUE);
    }  

    // verify digit length does not exceed int range
    if (length > maxlength) { 
        return false; 
    }

    // verify that all characters are numbers
    if (maxlength == 11 && length == 1) {
        return false;
    }
    for (int num = i; num < length; num++) {
        char c = str.charAt(num);
        if (c < '0' || c > '9') {
            return false;
        }
    }

    // verify that number value is within int range
    if (length == maxlength) {
        for (; i < length; i++) {
            if (str.charAt(i) < maxnum.charAt(i)) {
                return true;
            }
            else if (str.charAt(i) > maxnum.charAt(i)) {
                return false;
            }
        }
    }
    return true;
}
 1
Author: Wayne,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-02-20 18:34:08

Jeśli korzystasz z API Androida, możesz użyć:

TextUtils.isDigitsOnly(str);
 1
Author: timxyz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-07-08 12:32:03

Uważam, że nie ma ryzyka napotkania wyjątku, ponieważ jak widać poniżej zawsze bezpiecznie parsujesz int do String, a nie na odwrót.

Więc:

  1. Ty sprawdź Czy każdy slot znaku w Twoim łańcuchu pasuje przynajmniej jeden z bohaterów {"0","1","2","3","4","5","6","7","8","9"}.

    if(aString.substring(j, j+1).equals(String.valueOf(i)))
    
  2. Ty suma Wszystkie razy, które napotkałeś w szczelinach powyżej postaci.

    digits++;
    
  3. I na koniec sprawdź czy czasy, które napotkałeś jako znaki są równe długości podanego ciągu.

    if(digits == aString.length())
    

A w praktyce mamy:

    String aString = "1234224245";
    int digits = 0;//count how many digits you encountered
    for(int j=0;j<aString.length();j++){
        for(int i=0;i<=9;i++){
            if(aString.substring(j, j+1).equals(String.valueOf(i)))
                    digits++;
        }
    }
    if(digits == aString.length()){
        System.out.println("It's an integer!!");
        }
    else{
        System.out.println("It's not an integer!!");
    }
    
    String anotherString = "1234f22a4245";
    int anotherDigits = 0;//count how many digits you encountered
    for(int j=0;j<anotherString.length();j++){
        for(int i=0;i<=9;i++){
            if(anotherString.substring(j, j+1).equals(String.valueOf(i)))
                    anotherDigits++;
        }
    }
    if(anotherDigits == anotherString.length()){
        System.out.println("It's an integer!!");
        }
    else{
        System.out.println("It's not an integer!!");
    }

A wyniki są następujące:

To liczba całkowita!!

To nie jest liczba całkowita!!

Podobnie, możesz sprawdzić, czy String jest float lub double, ale w tych przypadkach musisz napotkać tylko jeden . (kropka) w łańcuchu i oczywiście sprawdzić czy digits == (aString.length()-1)

Ponownie, nie ma ryzyka wystąpienia wyjątku parsowania tutaj, ale jeśli planujesz parsowanie łańcucha znaków, o którym wiadomo, że zawiera liczbę (powiedzmy int typ danych), musisz najpierw sprawdzić, czy pasuje do typu danych. W przeciwnym razie musisz go rzucić.

Mam nadzieję, że pomogłem

 1
Author: mark_infinite,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-06-20 09:12:55

Inna opcja:

private boolean isNumber(String s) {
    boolean isNumber = true;
    for (char c : s.toCharArray()) {
        isNumber = isNumber && Character.isDigit(c);
    }
    return isNumber;
}
 1
Author: Gabriel Kaffka,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-06-14 14:52:22

To, co zrobiłeś działa, ale prawdopodobnie nie powinieneś zawsze sprawdzać w ten sposób. Rzucanie WYJĄTKÓW powinno być zarezerwowane dla" wyjątkowych " sytuacji (może to pasuje do twojego przypadku) i jest bardzo kosztowne pod względem wydajności.

 0
Author: lucas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2008-10-25 23:12:38

To działa tylko dla dodatnich liczb całkowitych.

public static boolean isInt(String str) {
    if (str != null && str.length() != 0) {
        for (int i = 0; i < str.length(); i++) {
            if (!Character.isDigit(str.charAt(i))) return false;
        }
    }
    return true;        
}
 0
Author: callejero,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-03-30 03:35:08

To mi pasuje. Po prostu, aby określić, czy ciąg jest prymitywny, czy liczba.

private boolean isPrimitive(String value){
        boolean status=true;
        if(value.length()<1)
            return false;
        for(int i = 0;i<value.length();i++){
            char c=value.charAt(i);
            if(Character.isDigit(c) || c=='.'){

            }else{
                status=false;
                break;
            }
        }
        return status;
    }
 0
Author: Niroshan Abeywickrama,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-12-19 09:04:31

Aby sprawdzić wszystkie znaki int, możesz po prostu użyć podwójnego negatywu.

If (!searchString.mecze("[^0-9]+$")) ...

[^0-9]+$ sprawdza, czy są jakieś znaki, które nie są liczbą całkowitą, więc test nie powiedzie się, jeśli to prawda. Tylko nie to i osiągniesz sukces.

 0
Author: Roger F. Gay,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-03-29 13:39:13

Widziałem tutaj wiele odpowiedzi, ale większość z nich jest w stanie określić, czy łańcuch jest liczbowy, ale nie sprawdzają, czy liczba jest w zakresie liczb całkowitych...

Dlatego mam na myśli coś takiego:

public static boolean isInteger(String str) {
    if (str == null || str.isEmpty()) {
        return false;
    }
    try {
        long value = Long.valueOf(str);
        return value >= -2147483648 && value <= 2147483647;
    } catch (Exception ex) {
        return false;
    }
}
 0
Author: Ellrohir,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-11-01 10:54:56

Gdy wyjaśnienia są ważniejsze od wykonania

Zauważyłem wiele dyskusji skupiających się na tym, jak wydajne są pewne rozwiązania, ale brak na Dlaczego ciąg znaków nie jest liczbą całkowitą. Ponadto wszyscy zdawali się zakładać, że liczba " 2.00 "nie jest równa"2". Mówiąc matematycznie i po ludzku, oni równi (chociaż Informatyka mówi, że nie są i nie bez powodu). Dlatego " Integer.parseInt " powyższe rozwiązania są słabe (w zależności na Państwa życzenie).

W każdym razie, aby oprogramowanie było mądrzejsze i bardziej przyjazne dla człowieka, musimy stworzyć oprogramowanie, które myśli tak jak my i wyjaśnia Dlaczego coś zawiodło. W tym przypadku:

public static boolean isIntegerFromDecimalString(String possibleInteger) {
possibleInteger = possibleInteger.trim();
try {
    // Integer parsing works great for "regular" integers like 42 or 13.
    int num = Integer.parseInt(possibleInteger);
    System.out.println("The possibleInteger="+possibleInteger+" is a pure integer.");
    return true;
} catch (NumberFormatException e) {
    if (possibleInteger.equals(".")) {
        System.out.println("The possibleInteger=" + possibleInteger + " is NOT an integer because it is only a decimal point.");
        return false;
    } else if (possibleInteger.startsWith(".") && possibleInteger.matches("\\.[0-9]*")) {
        if (possibleInteger.matches("\\.[0]*")) {
            System.out.println("The possibleInteger=" + possibleInteger + " is an integer because it starts with a decimal point and afterwards is all zeros.");
            return true;
        } else {
            System.out.println("The possibleInteger=" + possibleInteger + " is NOT an integer because it starts with a decimal point and afterwards is not all zeros.");
            return false;
        }
    } else if (possibleInteger.endsWith(".")  && possibleInteger.matches("[0-9]*\\.")) {
        System.out.println("The possibleInteger="+possibleInteger+" is an impure integer (ends with decimal point).");
        return true;
    } else if (possibleInteger.contains(".")) {
        String[] partsOfPossibleInteger = possibleInteger.split("\\.");
        if (partsOfPossibleInteger.length == 2) {
            //System.out.println("The possibleInteger=" + possibleInteger + " is split into '" + partsOfPossibleInteger[0] + "' and '" + partsOfPossibleInteger[1] + "'.");
            if (partsOfPossibleInteger[0].matches("[0-9]*")) {
                if (partsOfPossibleInteger[1].matches("[0]*")) {
                    System.out.println("The possibleInteger="+possibleInteger+" is an impure integer (ends with all zeros after the decimal point).");
                    return true;
                } else if (partsOfPossibleInteger[1].matches("[0-9]*")) {
                    System.out.println("The possibleInteger=" + possibleInteger + " is NOT an integer because it the numbers after the decimal point (" + 
                                partsOfPossibleInteger[1] + ") are not all zeros.");
                    return false;
                } else {
                    System.out.println("The possibleInteger=" + possibleInteger + " is NOT an integer because it the 'numbers' after the decimal point (" + 
                            partsOfPossibleInteger[1] + ") are not all numeric digits.");
                    return false;
                }
            } else {
                System.out.println("The possibleInteger=" + possibleInteger + " is NOT an integer because it the 'number' before the decimal point (" + 
                        partsOfPossibleInteger[0] + ") is not a number.");
                return false;
            }
        } else {
            System.out.println("The possibleInteger="+possibleInteger+" is NOT an integer because it has a strange number of decimal-period separated parts (" +
                    partsOfPossibleInteger.length + ").");
            return false;
        }
    } // else
    System.out.println("The possibleInteger='"+possibleInteger+"' is NOT an integer, even though it has no decimal point.");
    return false;
}
}

Kod badania:

String[] testData = {"0", "0.", "0.0", ".000", "2", "2.", "2.0", "2.0000", "3.14159", ".0001", ".", "$4.0", "3E24", "6.0221409e+23"};
int i = 0;
for (String possibleInteger : testData ) {
    System.out.println("");
    System.out.println(i + ". possibleInteger='" + possibleInteger +"' isIntegerFromDecimalString=" + isIntegerFromDecimalString(possibleInteger));
    i++;
}
 0
Author: Tihamer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-06-30 17:02:31

Nie lubię metody z regex, ponieważ regex nie może sprawdzać zakresów (Integer.MIN_VALUE, Integer.MAX_VALUE).

Jeśli oczekujesz wartości int w większości przypadków, a nie INT jest czymś niezwykłym, proponuję wersję z Integer.valueOf lub Integer.parseInt z NumberFormatException. Zaletą tego podejścia - Twój kod ma dobrą czytelność:

public static boolean isInt(String s) {
  try {
    Integer.parseInt(s);
    return true;
  } catch (NumberFormatException nfe) {
    return false;
  }
}

Jeśli chcesz sprawdzić, czy String jest liczbą całkowitą i dbać o perfomance, najlepszym sposobem będzie użycie java JDK implementacji Integer.parseInt, ale niewiele zmodyfikowanej (zastąpienie throw przez return false):

Funkcja ta ma dobrą perfomencję i odpowiedni wynik:

   public static boolean isInt(String s) {
    int radix = 10;

    if (s == null) {
        return false;
    }

    if (radix < Character.MIN_RADIX) {
        return false;
    }

    if (radix > Character.MAX_RADIX) {
        return false;
    }

    int result = 0;
    boolean negative = false;
    int i = 0, len = s.length();
    int limit = -Integer.MAX_VALUE;
    int multmin;
    int digit;

    if (len > 0) {
        char firstChar = s.charAt(0);
        if (firstChar < '0') { // Possible leading "+" or "-"
            if (firstChar == '-') {
                negative = true;
                limit = Integer.MIN_VALUE;
            } else if (firstChar != '+')
                return false;

            if (len == 1) // Cannot have lone "+" or "-"
                return false;
            i++;
        }
        multmin = limit / radix;
        while (i < len) {
            // Accumulating negatively avoids surprises near MAX_VALUE
            digit = Character.digit(s.charAt(i++), radix);
            if (digit < 0) {
                return false;
            }
            if (result < multmin) {
                return false;
            }
            result *= radix;
            if (result < limit + digit) {
                return false;
            }
            result -= digit;
        }
    } else {
        return false;
    }
    return true;
}
 0
Author: Balconsky,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-07-05 12:54:31