243

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

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

それは私だけですか、それともこれは少しハックっぽいですか?より良い方法は何ですか?


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

4

40 に答える 40

184

潜在的なオーバーフローの問題を心配していない場合、この関数はを使用するよりも約20〜30倍速く実行されます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;
}
于 2008-10-25T23:32:46.463 に答える
67

あなたはそれを持っていますが、キャッチする必要がありますNumberFormatException.

于 2008-10-25T23:03:34.667 に答える
41

早速ベンチマークを行いました。複数のメソッドをポップバックし始め、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 (注: 毎回パターンを再コンパイルします)

投稿者Jonas: 16

Jonas Kのソリューションも最も堅牢であることに同意します。彼が勝ったようです:)

于 2008-10-26T01:18:04.880 に答える
38
org.apache.commons.lang.StringUtils.isNumeric 

Java の標準ライブラリには、そのようなユーティリティ関数が本当に欠けていますが、

Apache Commons は、すべての Java プログラマーにとって「なくてはならない」ものだと思います。

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

于 2008-10-27T10:03:38.423 に答える
37

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

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
于 2011-09-06T17:55:15.970 に答える
24

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

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

文字ごとのチェックは、「まったく整数ではない」ケースを効率的に拒否し、「整数であるが Java が処理できない」ケースをより遅い例外ルートで捕捉するようにします。これも少し手作業で行うことができますが、かなり複雑になります。

于 2008-10-26T07:26:01.377 に答える
20

正規表現に関するコメントは 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();
    }
}
于 2008-10-26T11:27:00.297 に答える
12

rally25rs answer からコードをコピーし、非整数データのテストをいくつか追加しました。結果は、Jonas Klemming によって投稿された方法に間違いなく有利です。私が最初に投稿した Exception メソッドの結果は、整数データが​​ある場合はかなり良いですが、そうでない場合は最悪であり、RegEx ソリューションの結果 (多くの人が使用していると思います)一貫して悪かった。コンパイルされた正規表現の例については、 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
于 2008-10-26T13:13:46.837 に答える
6

string クラスの 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
于 2012-12-13T21:41:50.603 に答える
6

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

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

個人的には、実装はヘルパー メソッドで取り除かれ、正確さが長さよりも優先されるため、私はあなたが持っているようなものを使用します (基本Exceptionクラスではなくベース クラスをキャッチすることを除いてNumberFormatException)。

于 2008-10-25T23:04:46.897 に答える
4

どうですか:

return Pattern.matches("-?\\d+", input);
于 2008-10-25T23:03:12.890 に答える
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
于 2017-03-23T19:54:18.570 に答える
3

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

if (Character.isDigit(string.charAt(0))) {
    //Do something with int
}
于 2014-03-18T02:19:39.860 に答える
3

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

于 2008-10-26T05:27:50.133 に答える
2

あなたはapache utilsを試すことができます

NumberUtils.isCreatable(myText)

こちらのJavadocを参照してください

于 2014-02-25T11:15:18.553 に答える
2

文字列が int 型に収まる整数を表しているかどうかを確認したい場合は、jonas の回答を少し変更して、Integer.MAX_VALUE よりも大きい整数または Integer.MIN_VALUE よりも小さい整数を表す文字列が返されるようにしました。間違い。例: "3147483647" は、3147483647 が 2147483647 より大きいため、false を返します。同様に、"-2147483649" も、-2147483649 が -2147483648 より小さいため、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;
}
于 2017-08-25T01:59:48.557 に答える
1

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

TextUtils.isDigitsOnly(str);
于 2015-07-08T12:32:03.883 に答える
1

int以下に示すように、常に安全に解析し、その逆は行わないため、例外が発生するリスクはゼロだと思いますString

そう:

  1. 文字列内の文字のすべてのスロットが、{ "0"、"1"、"2"、"3"、"4"、"5"、"6"、"7"、 "8","9"} .

    if(aString.substring(j, j+1).equals(String.valueOf(i)))
    
  2. 上記の文字のスロットで遭遇したすべての時間を合計します。

    digits++;
    
  3. 最後に、文字として整数に遭遇した回数が、指定された文字列の長さと等しいかどうかを確認します。

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

結果は次のとおりです。

整数です!!

整数じゃない!!

同様に、 aStringが afloatまたは aであるかどうかを検証できますdoubleが、その場合は1 つだけに遭遇する必要があります。(ドット)文字列で、もちろんチェックします digits == (aString.length()-1)

繰り返しになりますが、ここで解析例外が発生するリスクはありませんが、数値を含む既知の文字列 ( intデータ型としましょう) を解析する予定がある場合は、最初にデータ型に適合するかどうかを確認する必要があります。それ以外の場合は、キャストする必要があります。

お役に立てば幸いです

于 2015-04-22T23:16:42.330 に答える
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;        
}
于 2012-03-30T03:29:19.200 に答える
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;
    }
于 2014-12-19T08:58:57.680 に答える
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++;
}
于 2018-06-30T17:02:31.160 に答える
0

kotlinの場合、isDigitsOnly() (Java の場合もTextUtils.isDigitsOnly()) of は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*/
于 2020-12-12T07:26:29.260 に答える
0

あなたがしたことは機能しますが、おそらく常にそのようにチェックするべきではありません。例外のスローは、「例外的な」状況のために予約する必要があり (おそらく、あなたのケースに当てはまるかもしれません)、パフォーマンスの点で非常にコストがかかります。

于 2008-10-25T23:12:38.643 に答える
-1
Number number;
try {
    number = NumberFormat.getInstance().parse("123");
} catch (ParseException e) {
    //not a number - do recovery.
    e.printStackTrace();
}
//use number
于 2008-10-26T08:07:15.367 に答える
-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;
}
于 2014-05-13T11:30:21.030 に答える
-1
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);
        }
    }
}
于 2016-04-11T05:05:08.860 に答える
-3
Integer.valueOf(string); 

ほとんどの場合、私のために働きます!

于 2008-10-26T00:11:57.853 に答える