检查String是否表示Java中的整数的最佳方法是什么?

时间:2008-10-25 22:58:49

标签: java string int

我通常使用以下习惯用法来检查String是否可以转换为整数。

public boolean isInteger( String input ) {
    try {
        Integer.parseInt( input );
        return true;
    }
    catch( Exception e ) {
        return false;
    }
}

这只是我,还是看起来有点hackish?什么是更好的方式?


请参阅我的回答(使用基准,基于earlier answer CodingWithSpike),以了解我为什么撤销我的立场并接受Jonas Klemming's answer此问题。我认为这个原始代码将被大多数人使用,因为它实现起来更快,更易于维护,但是当提供非整数数据时,它会慢一个数量级。

40 个答案:

答案 0 :(得分:156)

如果您不关心潜在的溢出问题,此功能的执行速度比使用Integer.parseInt()快20-30倍。

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;
}

答案 1 :(得分:57)

你拥有它,但你应该只抓住NumberFormatException

答案 2 :(得分:35)

做了快速基准测试。除非你开始弹出多个方法并且JVM必须做很多工作才能使执行堆栈到位,否则异常实际上并不是那种费用。当采用相同的方法时,他们的表现并不差。

 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;
 }

输出:

  

ByException:31

     

ByRegex:453(注意:每次重新编译模式)

     

ByJonas:16

我同意Jonas K的解决方案也是最强大的。看起来他赢了:)

答案 3 :(得分:35)

因为有可能人们仍然访问这里并且在基准测试后会对Regex产生偏见......所以我将提供一个更新版本的基准测试,以及Regex的编译版本。与之前的基准测试相反,这一点显示Regex解决方案实际上具有始终如一的良好性能。

从比尔蜥蜴复制并更新编译版本:

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;
}

结果:

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

答案 4 :(得分:30)

org.apache.commons.lang.StringUtils.isNumeric 

尽管Java的标准库确实错过了这样的实用函数

我认为Apache Commons对每个Java程序员来说都是“必备”

太糟糕了,它还没有移植到Java5

答案 5 :(得分:22)

部分取决于你的意思“可以转换为整数”。

如果你的意思是“可以转换为Java中的int”,那么Jonas的答案是一个良好的开端,但还没有完成这项工作。例如,它将通过99999999999999999999999999999。我会在方法结束时从你自己的问题中添加正常的try / catch调用。

逐字符检查将有效地拒绝“根本不是整数”的情况,留下“它是一个整数,但Java无法处理它”的情况被慢速异常路由捕获。您也可以手动执行此操作,但它会更复杂很多

答案 6 :(得分:15)

只有一条关于regexp的评论。这里提供的每个例子都是错的!如果你想使用正则表达式,不要忘记编译模式需要花费很多时间。这样:

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

还有这个:

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

导致在每个方法调用中编译模式。要正确使用它,请按照:

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();
    }
}

答案 7 :(得分:12)

我从rally25rs回复中复制了代码,并为非整数数据添加了一些测试。无可否认,结果有利于Jonas Klemming发布的方法。当你有整数数据时,我最初发布的Exception方法的结果非常好,但是当你没有整数数据时它们是最差的,而RegEx解决方案的结果(我敢打赌很多人使用) 一直坏。有关已编译的正则表达式示例,请参阅Felipe's answer,这要快得多。

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;
}

结果:

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

答案 8 :(得分:8)

有番石榴版:

import com.google.common.primitives.Ints;

Integer intValue = Ints.tryParse(stringValue);

如果无法解析字符串,它将返回null而不是抛出异常。

答案 9 :(得分:6)

这个更短,但更短并不一定更好(并且它不会捕获超出范围的整数值,as pointed out in danatel's comment):

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

就个人而言,由于实现是通过辅助方法进行的,并且正确性超过了长度,我只会选择你所拥有的东西(减去基础Exception类而不是NumberFormatException)。

答案 10 :(得分:6)

您可以使用字符串类的matches方法。 [0-9]表示它可以是的所有值,+表示它必须至少有一个字符长,而*表示它可以是零个或多个字符长。

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

答案 11 :(得分:4)

这是Jonas Klemming的Java 8变体回答:

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)));
}

测试代码:

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));
    });
}

测试代码的结果:

        1231231 true
    -1232312312 true
   +12313123131 true
  qwqe123123211 false
              2 true
  0000000001111 true
                false
           123- false
          ++123 false
         123-23 false
           null false
          +-123 false

答案 12 :(得分:3)

如果您的String数组包含纯整数和字符串,则下面的代码应该有效。你只需要看第一个角色。 例如[ “4”, “44”, “ABC”, “77”, “键”]

if (Character.isDigit(string.charAt(0))) {
    //Do something with int
}

答案 13 :(得分:3)

您也可以使用Scanner类,并使用hasNextInt() - 这样您就可以测试其他类型,如浮点数等。

答案 14 :(得分:2)

您只需检查 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 
 }  

答案 15 :(得分:2)

您可以尝试使用apache utils

NumberUtils.isNumber( myText)

See the javadoc here

答案 16 :(得分:1)

这是对 Jonas &#39;的修改。检查字符串是否在范围内以强制转换为整数的代码。

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;
}

答案 17 :(得分:1)

另一种选择:

private boolean isNumber(String s) {
    boolean isNumber = true;
    for (char c : s.toCharArray()) {
        isNumber = isNumber && Character.isDigit(c);
    }
    return isNumber;
}

答案 18 :(得分:1)

如果要检查字符串是否表示适合int类型的整数,我对jonas的答案做了一点修改,以便表示整数大于Integer.MAX_VALUE或小于Integer.MIN_VALUE的字符串,现在将返回false。例如:“3147483647”将返回false,因为3147483647大于2147483647,同样,“ - 2147483649”也将返回false,因为-2147483649小于-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;
}

答案 19 :(得分:1)

如果您使用的是Android API,则可以使用:

TextUtils.isDigitsOnly(str);

答案 20 :(得分:1)

怎么样:

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

答案 21 :(得分:1)

您可能还需要考虑帐户中的用例:

如果大多数时候您希望数字有效,那么捕获异常只会在尝试转换无效数字时导致性能开销。调用某些isInteger()方法然后使用Integer.parseInt()转换将总是导致有效数字的性能开销 - 字符串被解析两次,一次通过检查,一次通过转换

答案 22 :(得分:0)

最近(今天)我需要找出一种快速的方法来完成此操作,当然,当肩膀上的猴子(良心)醒来时,我将使用异常方法来缓解这种不适,这让我很失望兔子洞没有例外并没有那么昂贵,实际上有时例外会更快(旧的AIX多处理器系统),但是不管它是优雅还是优雅,所以我做了一些我年轻的孩子从未做过的事情,而令我惊讶的是,这里的任何人都没有做过(如果有人和我做过,就道歉我真的找不到了,错过了):所以我认为我们都错过了什么?看看JRE是如何实现的,是的,他们抛出了异常,但是我们总是可以跳过这一部分。

10年前的我这个年轻的人会觉得这是在他身下,但是他又一次大声地炫耀,气质差,神情复杂,所以就是这样。

我把它放在这里是为了将来任何人来这里谋福利。这是我发现的:

public static int parseInt(String s, int radix) throws NumberFormatException
{
    /*
     * WARNING: This method may be invoked early during VM initialization
     * before IntegerCache is initialized. Care must be taken to not use
     * the valueOf method.
     */

    if (s == null) {
        throw new NumberFormatException("null");
    }

    if (radix < Character.MIN_RADIX) {
        throw new NumberFormatException("radix " + radix +
                                        " less than Character.MIN_RADIX");
    }

    if (radix > Character.MAX_RADIX) {
        throw new NumberFormatException("radix " + radix +
                                        " greater than Character.MAX_RADIX");
    }

    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 != '+')
                throw NumberFormatException.forInputString(s);

            if (len == 1) // Cannot have lone "+" or "-"
                throw NumberFormatException.forInputString(s);
            i++;
        }
        multmin = limit / radix;
        while (i < len) {
            // Accumulating negatively avoids surprises near MAX_VALUE
            digit = Character.digit(s.charAt(i++),radix);
            if (digit < 0) {
                throw NumberFormatException.forInputString(s);
            }
            if (result < multmin) {
                throw NumberFormatException.forInputString(s);
            }
            result *= radix;
            if (result < limit + digit) {
                throw NumberFormatException.forInputString(s);
            }
            result -= digit;
        }
    } else {
        throw NumberFormatException.forInputString(s);
    }
    return negative ? result : -result;
}

答案 23 :(得分:0)

对于 kotlin isDigitsOnly() (对于Java的TextUtils.isDigitsOnly() String总是返回false,它带有负号尽管其余字符只能是数字。例如-

/** For kotlin*/
var str = "-123" 
str.isDigitsOnly()  //Result will be false 

/** For Java */
String str = "-123"
TextUtils.isDigitsOnly(str) //Result will be also false 

因此,我对此进行了快速修复-

 var isDigit=str.matches("-?\\d+(\\.\\d+)?".toRegex()) 
/** Result will be true for now*/

答案 24 :(得分:0)

对@Jonas K anwser的改进,此功能将排除像"*"这样的单个运算符。

public boolean isInteger(String str) {
    // null pointer
    if (str == null) {
        return false;
    }
    int len = str.length();
    // empty string
    if (len == 0) {
        return false;
    }
    // one digit, cannot begin with 0
    if (len == 1) {
        char c = str.charAt(0);
        if ((c < '1') || (c > '9')) {
            return false;
        }
    }

    for (int i = 0; i < len; i++) {
        char c = str.charAt(i);
        // check positive, negative sign
        if (i == 0) {
            if (c == '-' || c == '+') {
                continue;
            }
        }
        // check each character matches [0-9]
        if ((c < '0') || (c > '9')) {
            return false;
        }
    }
    return true;
}

答案 25 :(得分:0)

您可以:

  1. 检查字符串是否为数字
  2. 检查被解析为long的时间是否太短
  3. 检查所得的long值是否足够小以足以由int表示

(假设由于某种原因您必须自己实施此操作:您可能应该首先看一下com.google.common.primitives.Ints.tryParse(String),看看它是否足以满足您的目的(如建议的in another answer)。)

// Credit to Rastislav Komara’s answer: https://stackoverflow.com/a/237895/1725151
private static final Pattern nonZero = Pattern.compile("^-?[1-9]\\d*$");

// See if `str` can be parsed as an `int` (does not trim)
// Strings like `0023` are rejected (leading zeros).
public static boolean parsableAsInt(@Nonnull String str) {
    if (str.isEmpty()) {
        return false;
    }
    if (str.equals("0")) {
        return true;
    }
    if (canParseAsLong(str)) {
        long value = Long.valueOf(str);
        if (value >= Integer.MIN_VALUE && value <= Integer.MAX_VALUE) {
            return true;
        }
    }
    return false;
}

private static boolean canParseAsLong(String str) {
    final int intMaxLength = 11;
    return str.length() <= intMaxLength && nonZero.matcher(str).matches();
}

此方法也可以转换为返回Optional<Integer>,这样您就不必在客户端代码中解析字符串两次(一次检查是否可行,第二次“真正”执行) )。例如:

if (canParseAsLong(str)) {
    long value = Long.valueOf(str);
    if (value >= Integer.MIN_VALUE && value <= Integer.MAX_VALUE) {
        return Optional.of((int) value);
    }
}

答案 26 :(得分:0)

我不喜欢使用正则表达式的方法,因为正则表达式无法检查范围(Integer.MIN_VALUEInteger.MAX_VALUE)。

如果在大多数情况下期望int值,但int并不罕见,那么我建议使用Integer.valueOfInteger.parseInt捕获NumberFormatException的版本。这种方法的优势-您的代码具有良好的可读性:

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

如果您需要检查String是否为整数,并关心性能,那么最好的方法是使用Integer.parseInt的java jdk实现,但只需进行少量修改(将throw替换为false即可):

此功能具有良好的性能和可靠的保证:

   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;
}

答案 27 :(得分:0)

当解释比表现更重要时

我注意到许多讨论都集中在某些解决方案的效率上,但是关于为什么的问题,没有一个字符串不是整数。同样,每个人似乎都假定数字“ 2.00”不等于“ 2”。从数学和人类的角度来讲,它们 是相等的(即使计算机科学说它们不是,并且有充分的理由)。这就是为什么上面的“ Integer.parseInt”解决方案比较弱(取决于您的要求)的原因。

无论如何,要使软件更智能,更人性化,我们需要创建像我们一样思考并解释失败原因的软件。在这种情况下:

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;
}
}

测试代码:

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++;
}

答案 28 :(得分:0)

这里有几个答案,试图解析为整数并捕获NumberFormatException,但您不应这样做。

那样,将在每次调用异常对象时创建异常对象并生成堆栈跟踪,并且它不是整数。

使用Java 8的更好方法是使用流:

boolean isInteger = returnValue.chars().allMatch(Character::isDigit);

答案 29 :(得分:0)

Number number;
try {
    number = NumberFormat.getInstance().parse("123");
} catch (ParseException e) {
    //not a number - do recovery.
    e.printStackTrace();
}
//use number

答案 30 :(得分:0)

is_number = true;
try {
  Integer.parseInt(mystr)
} catch (NumberFormatException  e) {
  is_number = false;
}

答案 31 :(得分:0)

我在这里看到了很多答案,但是大多数答案都能确定字符串是否为数字,但是它们无法检查数字是否在整数范围内...

因此我的目的是这样的:

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;
    }
}

答案 32 :(得分:0)

你做了什么,但你可能不应该总是那样检查。抛出异常应保留用于“特殊”情况(可能适合您的情况),并且在性能方面非常昂贵。

答案 33 :(得分:0)

发现这可能有帮助:

public static boolean isInteger(String self) {
    try {
        Integer.valueOf(self.trim());
        return true;
    } catch (NumberFormatException nfe) {
        return false;
    }
}

答案 34 :(得分:0)

我相信遇到异常的风险为零,因为正如您在下面看到的那样,您始终可以安全地将int解析为String,而不是相反。

所以:

  1. 如果字符串中的每个字符插槽至少匹配,则检查 其中一个字符 {&#34; 0&#34;,&#34; 1&#34;,&#34; 2&#34;,&#34; 3&#34;,&#34; 4&# 34;,&#34; 5&#34;&#34; 6&#34;&#34; 7&#34;&#34; 8&#34;&#34; 9&#34;}

    if(aString.substring(j, j+1).equals(String.valueOf(i)))
    
  2. 总和您在上述广告位中遇到的所有时间 字符。

    digits++;
    
  3. 最后你检查你遇到的时间是否为整数 字符等于给定字符串的长度。

    if(digits == aString.length())
    
  4. 在实践中我们有:

        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!!");
        }
    

    结果是:

      

    这是一个整数!!

         

    它不是整数!!

    同样,您可以验证Stringfloat还是double,但在这种情况下,您必须遇到只有一个。(点)在字符串中,当然要检查digits == (aString.length()-1)

      

    同样,这里遇到了解决异常的零风险,但是如果你计划解析一个已知包含数字的字符串(让我们说 int 数据类型)您必须首先检查它是否适合数据类型。否则你必须施展它。

    我希望我帮助

答案 35 :(得分:0)

要检查所有int字符,您只需使用双重否定字符。

if(!searchString.matches(&#34; [^ 0-9] + $&#34;))...

[^ 0-9] + $检查是否有任何不是整数的字符,因此如果测试成立则测试失败。只是不那样,你就成功了。

答案 36 :(得分:0)

这对我有用。只需识别String是基元还是数字。

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;
    }

答案 37 :(得分:0)

这只适用于正整数。

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;        
}

答案 38 :(得分:-1)

对于那些像我一样到达这里的读者,在问题问题的几年后,我对这个问题有一个更通用的解决方案。

/**
 * Checks, if the string represents a number.
 *
 * @param string the string
 * @return true, if the string is a number
 */
public static boolean isANumber(final String string) {
    if (string != null) {
        final int length = string.length();
        if (length != 0) {
            int i = 0;
            if (string.charAt(0) == '-') {
                if (length == 1) {
                    return false;
                }
                i++;
            }
            for (; i < length; i++) {
                final char c = string.charAt(i);
                if ((c <= PERIOD) || ((c >= COLON))) {
                    final String strC = Character.toString(c).toUpperCase();
                    final boolean isExponent = strC.equals("E");
                    final boolean isPeriod = (c == PERIOD);
                    final boolean isPlus = (c == PLUS);

                    if (!isExponent && !isPeriod && !isPlus) {
                        return false;
                    }
                }
            }
            return true;
        }
    }
    return false;
}

答案 39 :(得分:-3)

Integer.valueOf(string); 

大部分时间都适合我!