web-dev-qa-db-ja.com

Javaで文字列が整数を表すかどうかを確認する最良の方法は何ですか?

通常、次のイディオムを使用して、文字列を整数に変換できるかどうかを確認します。

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

それは私だけですか、またはこれは少しハックのように見えますか?より良い方法は何ですか?


以前の回答 による CodingWithSpike に基づくベンチマークでの回答を参照して、自分の立場を逆転させて受け入れた理由を確認してください Jonas Klemmingの回答 この問題に。この元のコードは、実装が速く、保守性が高いため、ほとんどの人が使用すると思いますが、非整数データが​​提供されると、桁違いに遅くなります。

197
Bill the Lizard

潜在的なオーバーフローの問題に関心がない場合、この関数は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;
}
158
Jonas Klemming

ありますが、NumberFormatExceptionのみをキャッチする必要があります。

59
Ovidiu Pacurar

簡単なベンチマークを行いました。複数のメソッドをポップバックし始め、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のソリューションも最も堅牢であることに同意します。彼が勝ったように見える:)

35
CodingWithSpike

人々はまだここを訪れ、ベンチマーク後に正規表現に偏る可能性があるので、...コンパイル済みの正規表現を使用して、ベンチマークの更新バージョンを提供します。これは以前のベンチマークとは対照的でしたが、これは正規表現ソリューションが一貫して良好なパフォーマンスを実際に持っていることを示しています。

Bill the Lizardからコピーされ、コンパイル済みバージョンで更新されました。

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
35
Felipe
org.Apache.commons.lang.StringUtils.isNumeric 

ただし、Javaの標準ライブラリはそのようなユーティリティ関数を実際に見逃しています

Apache CommonsはすべてのJavaプログラマーにとって「必須」だと思います

残念ながら、まだJava5に移植されていません

32
Łukasz Bownik

「整数に変換できる」という意味に一部依存します。

「Javaでintに変換できる」という意味であれば、Jonasからの回答は良い出発点ですが、仕事を終わらせることはできません。たとえば、9999999999999999999999999999999999を渡します。メソッドの最後に、独自の質問から通常のtry/catch呼び出しを追加します。

文字ごとのチェックは「整数ではない」ケースを効率的に拒否し、「それは整数ですが、Javaは処理できません」ケースを低速の例外ルートでキャッチします。 couldこれも手作業で行いますが、lotより複雑になります。

22
Jon Skeet

正規表現に関するコメントを1つだけ。ここで提供されるすべての例は間違っています!。正規表現を使用する場合は、パターンのコンパイルに時間がかかることを忘れないでください。この:

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

Rally25rsの回答からコードをコピーし、非整数データのテストを追加しました。結果は間違いなく、Jonas Klemmingが投稿した方法を支持しています。私が最初に投稿したExceptionメソッドの結果は、整数データが​​ある場合はかなり良いですが、そうでない場合は最悪です。 一貫して悪い。コンパイル済みの正規表現の例については、 Felipeの答え を参照してください。これははるかに高速です。

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
12
Bill the Lizard

グアバ版があります:

import com.google.common.primitives.Ints;

Integer intValue = Ints.tryParse(stringValue);

文字列の解析に失敗した場合、例外をスローする代わりにnullを返します。

9
abalcerek

これは短くなりますが、必ずしも短くなるとは限りません(範囲外の整数値をキャッチすることはできません danatelのコメントで指摘されているように ):

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

個人的には、実装はヘルパーメソッドで削除され、正確さは長さよりも重要なので、私はあなたが持っているもの(ExceptionではなくベースNumberFormatExceptionクラスをキャッチする)のようなものを選びます。

6
Jonny Buchanan

文字列クラスのmatchesメソッドを使用できます。 [0-9]は可能なすべての値を表し、+は少なくとも1文字の長さでなければならないことを意味し、*は0文字以上の長さであることを意味します。

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
Kaitie

これは、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
4
gil.fernandes

Scanner クラスを使用し、 hasNextInt() を使用することもできます。これにより、floatなどの他のタイプもテストできます。

3

文字列配列に純粋な整数と文字列が含まれている場合、以下のコードが機能するはずです。最初のキャラクターを見るだけです。例えば["4"、 "44"、 "abc"、 "77"、 "bond"]

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

確認するだけです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
duggu

Apache utilsを試すことができます

NumberUtils.isNumber( myText)

こちらのjavadocを参照

2
borjab

どうですか:

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

おそらく、ユースケースも考慮する必要があります。

ほとんどの場合、数値が有効であると予想される場合、例外をキャッチしても、無効な数値を変換しようとしたときにパフォーマンスのオーバーヘッドが発生するだけです。いくつかのisInteger()メソッドを呼び出してからInteger.parseInt()を使用して変換すると、alwaysは有効な数値のパフォーマンスオーバーヘッドを引き起こします。 。

1
mobra66

Android AP​​Iを使用している場合は、次を使用できます。

TextUtils.isDigitsOnly(str);
1
timxyz

別のオプション:

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

文字列がint型に収まる整数を表すかどうかを確認したい場合、Jonasの答えに少し変更を加えたため、Integer.MAX_VALUEより大きい整数またはInteger.MIN_VALUEより小さい整数を表す文字列が返されます偽。たとえば、3147483647は2147483647よりも大きいため、「3147483647」はfalseを返します。同様に、-2147483649は-2147483649が-2147483648よりも小さいため、「-2147483649」もfalseを返します。

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

これは、文字列が整数にキャストされる範囲内にあるかどうかをチェックするJonas 'コードの修正です。

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
Wayne

私はここで多くの答えを見てきましたが、それらのほとんどは文字列が数値であるかどうかを判断できますが、数値が整数範囲にあるかどうかのチェックに失敗します...

したがって、私はこのようなものを目指しています:

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
Ellrohir
public class HelloWorld{

    static boolean validateIP(String s){
        String[] value = s.split("\\.");
        if(value.length!=4) return false;
        int[] v = new int[4];
        for(int i=0;i<4;i++){
            for(int j=0;j<value[i].length();j++){
                if(!Character.isDigit(value[i].charAt(j))) 
                 return false;
            }
            v[i]=Integer.parseInt(value[i]);
            if(!(v[i]>=0 && v[i]<=255)) return false;
        }
        return true;
    }

    public static void main(String[] argv){
        String test = "12.23.8.9j";
        if(validateIP(test)){
            System.out.println(""+test);
        }
    }
}
0
salaheddine

これは私のために動作します。文字列がプリミティブであるか数字であるかを識別するために。

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

パフォーマンスよりも説明が重要な場合

特定のソリューションがどれほど効率的であるかを中心とした多くの議論に気づきましたが、文字列が整数ではないwhyには何もありません。また、誰もが数字「2.00」が「2」に等しくないと仮定したようです。数学的にも人間的にも、それらは等しい(コンピューターサイエンスによれば、そうではないと、正当な理由で)。これが、上の「Integer.parseInt」ソリューションが弱い理由です(要件によって異なります)。

とにかく、ソフトウェアをよりスマートで人間に優しいものにするために、私たちがやっているように考え、説明したソフトウェアを作成する必要がありますwhy何かが失敗しました。この場合:

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++;
}
0
Tihamer
is_number = true;
try {
  Integer.parseInt(mystr)
} catch (NumberFormatException  e) {
  is_number = false;
}
0
Ricardo Acras

あなたがしたことは動作しますが、おそらくそのように常にチェックするべきではありません。例外をスローすることは、「例外的な」状況のために予約されている必要があります(ただし、それはおそらくあなたの場合に当てはまるでしょう)。

0
lucas

正規表現では範囲(Integer.MIN_VALUEInteger.MAX_VALUE)をチェックできないため、正規表現を使用したメソッドは好きではありません。

ほとんどの場合int値を期待し、intは珍しいことではない場合、Integer.valueOfまたはNumberFormatExceptionをキャッチするInteger.parseIntを含むバージョンをお勧めします。このアプローチの利点-コードは読みやすくなっています。

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

Stringが整数であるかどうかを確認する必要があり、パフォーマンスに注意する必要がある場合、Java jdk実装のInteger.parseIntを使用することをお勧めしますが、変更はほとんどありません(スローを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;
}
0
Balconsky

すべてのint文字を確認するには、単純に二重否定を使用できます。

if(!searchString.matches( "[^ 0-9] + $"))...

[^ 0-9] + $は、整数ではない文字があるかどうかを確認するため、trueの場合、テストは失敗します。それだけではなく、成功すると真実になります。

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

以下に示すように、intからStringを常に安全に解析し、その逆ではないため、例外が発生するリスクはないと考えています。

そう:

  1. check文字列内のすべての文字スロットが少なくとも1つの文字{"0"、 "1"、 "2"、 "3"、 "4"に一致する場合、「5」、「6」、「7」、「8」、「9」}

    if(aString.substring(j, j+1).equals(String.valueOf(i)))
    
  2. あなたはsumスロットで上記のキャラクターに遭遇したすべての時間。

    digits++;
    
  3. そして最後に、文字として整数に遭遇した時間が与えられた文字列の長さと等しい場合、checkになります。

    if(digits == aString.length())
    

そして実際には:

    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であるかを検証できますが、これらの場合はに1つだけ.(ドット)を見つける必要があります文字列、そしてもちろんdigits == (aString.length()-1)

繰り返しますが、ここで構文解析例外が発生するリスクはありませんが、数値を含むことがわかっている文字列(intデータ型など)の構文解析を計画している場合は、まずそれを確認する必要がありますデータ型に適合します。それ以外の場合は、キャストする必要があります。

私が助けたことを願っています

0
mark_infinite

これは役に立つかもしれません:

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

これは正の整数に対してのみ機能します。

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
callejero