102

Integer.parseInt()文字列をintに変換するためによく使用するプロジェクトがあります。何かがうまくいかない場合(たとえば、Stringは数字ではなく文字aなど)、このメソッドは例外をスローします。ただし、コード内のあらゆる場所で例外を処理する必要がある場合、これは非常にすぐに醜く見え始めます。これをメソッドに入れたいのですが、変換がうまくいかなかったことを示すためにクリーンな値を返す方法がわかりません。

C ++では、intへのポインターを受け入れ、メソッド自体がtrueまたはfalseを返すようにするメソッドを作成できました。しかし、私が知る限り、これはJavaでは不可能です。true / false変数と変換された値を含むオブジェクトを作成することもできますが、これも理想的ではないようです。同じことがグローバル値にも当てはまり、これによりマルチスレッドで問題が発生する可能性があります。

それで、これを行うためのクリーンな方法はありますか?

4

26 に答える 26

153

解析の失敗時に戻るのではIntegerなく、を返すことができます。intnull

Javaが内部で例外をスローせずにこれを行う方法を提供していないのは残念ですが、例外を非表示にすることはできますが(キャッチしてnullを返すことで)、数百を解析している場合はパフォーマンスの問題になる可能性があります数千ビットのユーザー提供データ。

編集:そのようなメソッドのコード:

public static Integer tryParse(String text) {
  try {
    return Integer.parseInt(text);
  } catch (NumberFormatException e) {
    return null;
  }
}

textnullの場合、これが何をするのかわからないことに注意してください。バグを表す場合(つまり、コードが無効な値を渡す可能性はありますが、nullを渡すことはできません)、例外をスローすることが適切であると考える必要があります。バグを表していない場合は、他の無効な値の場合と同じように、おそらくnullを返す必要があります。

もともとこの答えはnew Integer(String)コンストラクターを使用していました。現在Integer.parseInt、ボクシング操作を使用しています。このようにして、小さな値はキャッシュされたIntegerオブジェクトにボックス化され、そのような状況でより効率的になります。

于 2009-09-28T09:02:57.460 に答える
38

数字でない場合、どのような行動を期待しますか?

たとえば、入力が数値でない場合に使用するデフォルト値があることが多い場合は、次のような方法が役立つ可能性があります。

public static int parseWithDefault(String number, int defaultVal) {
  try {
    return Integer.parseInt(number);
  } catch (NumberFormatException e) {
    return defaultVal;
  }
}

入力を解析できない場合の異なるデフォルトの動作に対して、同様のメソッドを作成できます。

于 2009-09-28T11:13:17.330 に答える
33

解析エラーをフェイルファストの状況として処理する必要がある場合もありますが、アプリケーション構成などの場合は、Apache Commons Lang3NumberUtilsを使用してデフォルト値で欠落している入力を処理することを好みます。

int port = NumberUtils.toInt(properties.getProperty("port"), 8080);
于 2013-09-27T18:44:10.497 に答える
17

例外の処理を回避するには、正規表現を使用して、最初にすべての数字があることを確認します。

//Checking for Regular expression that matches digits
if(value.matches("\\d+")) {
     Integer.parseInt(value);
}
于 2013-08-20T22:23:31.947 に答える
14

グアバInts.tryParse()にあります。数値以外の文字列では例外をスローしませんが、null文字列では例外をスローします。

于 2013-10-03T18:12:39.367 に答える
4

次のようなものを使用できるかもしれません:

public class Test {
public interface Option<T> {
    T get();

    T getOrElse(T def);

    boolean hasValue();
}

final static class Some<T> implements Option<T> {

    private final T value;

    public Some(T value) {
        this.value = value;
    }

    @Override
    public T get() {
        return value;
    }

    @Override
    public T getOrElse(T def) {
        return value;
    }

    @Override
    public boolean hasValue() {
        return true;
    }
}

final static class None<T> implements Option<T> {

    @Override
    public T get() {
        throw new UnsupportedOperationException();
    }

    @Override
    public T getOrElse(T def) {
        return def;
    }

    @Override
    public boolean hasValue() {
        return false;
    }

}

public static Option<Integer> parseInt(String s) {
    Option<Integer> result = new None<Integer>();
    try {
        Integer value = Integer.parseInt(s);
        result = new Some<Integer>(value);
    } catch (NumberFormatException e) {
    }
    return result;
}

}
于 2009-09-28T10:18:37.280 に答える
4

質問への回答を読んだ後、parseIntメソッドをカプセル化またはラップする必要はなく、おそらく良い考えではないと思います。

Jonが提案したように、「null」を返すこともできますが、それは多かれ少なかれ、try/catch構造をnullチェックに置き換えています。エラー処理を「忘れる」場合の動作にはわずかな違いがあります。例外をキャッチしない場合、割り当てはなく、左側の変数は古い値を保持します。nullをテストしないと、JVM(NPE)に見舞われる可能性があります。

あくびの提案は私にはもっとエレガントに見えます。なぜなら、いくつかのエラーや例外的な状態を知らせるためにnullを返すのは好きではないからです。次に、問題を示す事前定義されたオブジェクトとの参照の同等性を確認する必要があります。しかし、他の人が主張するように、もう一度「チェックするのを忘れて」文字列が解析できない場合、プログラムは「ERROR」または「NULL」オブジェクト内にラップされたintを継続します。

Nikolayのソリューションはさらにオブジェクト指向であり、他のラッパークラスのparseXXXメソッドでも機能します。しかし、結局、彼はNumberFormatExceptionをOperationNotSupported例外に置き換えただけです。ここでも、解析できない入力を処理するには、try/catchが必要です。

したがって、プレーンなparseIntメソッドをカプセル化しないという私の結論です。いくつかの(アプリケーションに依存する)エラー処理も追加できる場合にのみカプセル化します。

于 2009-09-28T11:12:40.340 に答える
2

非常に簡単に必要なC++の動作を複製することもできます

public static boolean parseInt(String str, int[] byRef) {
    if(byRef==null) return false;
    try {
       byRef[0] = Integer.parseInt(prop);
       return true;
    } catch (NumberFormatException ex) {
       return false;
    }
}

次のような方法を使用します。

int[] byRef = new int[1];
boolean result = parseInt("123",byRef);

その後、変数はすべて問題なく実行され、解析された値が含まれているresult場合はtrueです。byRef[0]

個人的には、例外をキャッチすることに固執します。

于 2009-09-28T11:06:15.080 に答える
1

私のJavaは少し錆びていますが、正しい方向に向けることができるかどうか見てみましょう。

public class Converter {

    public static Integer parseInt(String str) {
        Integer n = null;

        try {
            n = new Integer(Integer.tryParse(str));
        } catch (NumberFormatException ex) {
            // leave n null, the string is invalid
        }

        return n;
    }

}

戻り値がnull、の場合、値が正しくありません。それ以外の場合は、有効ながありますInteger

于 2009-09-28T09:10:04.147 に答える
1

nullJon Skeetの答えは問題ありませんが、 Integerオブジェクトを返すのは好きではありません。これは使いにくいと思います。Java 8以降、(私の意見では)より良いオプションがありますOptionalInt

public static OptionalInt tryParse(String value) {
 try {
     return OptionalInt.of(Integer.parseInt(value));
  } catch (NumberFormatException e) {
     return OptionalInt.empty();
  }
}

これにより、値が利用できない場合を処理する必要があることが明示されます。将来、この種の関数がJavaライブラリに追加されることを望んでいますが、それが実現するかどうかはわかりません。

于 2016-07-19T07:11:39.830 に答える
1

parseIntメソッドをフォークするのはどうですか?

簡単です。コンテンツをコピーして新しいユーティリティに貼り付けるだけです。このユーティリティは、スローを返すIntegerOptional<Integer>、スローをリターンに置き換えます。基になるコードに例外はないようですが、チェックすることをお勧めします。

例外処理全体をスキップすることで、無効な入力にかかる時間を節約できます。また、この方法はJDK 1.0以降に存在するため、最新の状態に保つために多くのことを行う必要はないでしょう。

于 2016-09-12T16:11:08.450 に答える
1

Java 8以降を使用している場合は、リリースしたばかりのライブラリ(https://github.com/robtimus/try-parse )を使用できます。例外のキャッチに依存しないint、long、booleanをサポートしています。GuavaのInts.tryParseとは異なり、https: //stackoverflow.com/a/38451745/1180351とよく似ていますが、より効率的です。

于 2019-04-28T11:53:45.403 に答える
1

java.util.functionJava 8にはサプライヤ関数を定義できるパッケージがあるため、誰かがより一般的なアプローチを探しているのかもしれません。次のように、サプライヤとデフォルト値を受け取る関数を作成できます。

public static <T> T tryGetOrDefault(Supplier<T> supplier, T defaultValue) {
    try {
        return supplier.get();
    } catch (Exception e) {
        return defaultValue;
    }
}

この関数を使用すると、例外がスローされないようにしながら、例外をスローする可能性のある任意の解析メソッドまたはその他のメソッドを実行できます。

Integer i = tryGetOrDefault(() -> Integer.parseInt(stringValue), 0);
Long l = tryGetOrDefault(() -> Long.parseLong(stringValue), 0l);
Double d = tryGetOrDefault(() -> Double.parseDouble(stringValue), 0d);
于 2020-10-23T08:45:16.553 に答える
0

私がこの問題を処理する方法は再帰的です。たとえば、コンソールからデータを読み取る場合:

Java.util.Scanner keyboard = new Java.util.Scanner(System.in);

public int GetMyInt(){
    int ret;
    System.out.print("Give me an Int: ");
    try{
        ret = Integer.parseInt(keyboard.NextLine());

    }
    catch(Exception e){
        System.out.println("\nThere was an error try again.\n");
        ret = GetMyInt();
    }
    return ret;
}
于 2012-03-08T00:27:52.193 に答える
0

次のような方法を検討することをお勧めします

 IntegerUtilities.isValidInteger(String s)

次に、適切と思われる方法で実装します。結果を持ち帰りたい場合(おそらくInteger.parseInt()を使用しているため)、配列トリックを使用できます。

 IntegerUtilities.isValidInteger(String s, int[] result)

ここで、result[0]をプロセスで見つかった整数値に設定します。

于 2009-09-28T11:46:31.363 に答える
0

これは、ニコライのソリューションにいくぶん似ています。

 private static class Box<T> {
  T me;
  public Box() {}
  public T get() { return me; }
  public void set(T fromParse) { me = fromParse; }
 }

 private interface Parser<T> {
  public void setExclusion(String regex);
  public boolean isExcluded(String s);
  public T parse(String s);
 }

 public static <T> boolean parser(Box<T> ref, Parser<T> p, String toParse) {
  if (!p.isExcluded(toParse)) {
   ref.set(p.parse(toParse));
   return true;
  } else return false;
 }

 public static void main(String args[]) {
  Box<Integer> a = new Box<Integer>();
  Parser<Integer> intParser = new Parser<Integer>() {
   String myExclusion;
   public void setExclusion(String regex) {
    myExclusion = regex;
   }
   public boolean isExcluded(String s) {
    return s.matches(myExclusion);
   }
   public Integer parse(String s) {
    return new Integer(s);
   }
  };
  intParser.setExclusion("\\D+");
  if (parser(a,intParser,"123")) System.out.println(a.get());
  if (!parser(a,intParser,"abc")) System.out.println("didn't parse "+a.get());
 }

mainメソッドはコードをデモします。パーサーインターフェイスを実装する別の方法は、明らかに、構築から「\ D +」を設定し、メソッドに何も行わないようにすることです。

于 2009-09-28T14:30:58.660 に答える
0

例外を回避するために、JavaのFormat.parseObjectメソッドを使用できます。以下のコードは、基本的にApacheCommonのIntegerValidatorクラスの簡略化されたバージョンです。

public static boolean tryParse(String s, int[] result)
{
    NumberFormat format = NumberFormat.getIntegerInstance();
    ParsePosition position = new ParsePosition(0);
    Object parsedValue = format.parseObject(s, position);

    if (position.getErrorIndex() > -1)
    {
        return false;
    }

    if (position.getIndex() < s.length())
    {
        return false;
    }

    result[0] = ((Long) parsedValue).intValue();
    return true;
}

好みに応じて、AtomicIntegerまたは配列トリックのいずれかを使用できます。int[]

これがそれを使用する私のテストです-

int[] i = new int[1];
Assert.assertTrue(IntUtils.tryParse("123", i));
Assert.assertEquals(123, i[0]);
于 2013-04-26T16:49:24.303 に答える
0

私も同じ問題を抱えていました。これは、ユーザーに入力を要求し、整数でない限り入力を受け入れないようにするために作成したメソッドです。私は初心者なので、コードが期待どおりに機能しない場合は、経験不足のせいにしてください。

private int numberValue(String value, boolean val) throws IOException {
    //prints the value passed by the code implementer
    System.out.println(value);
    //returns 0 is val is passed as false
    Object num = 0;
    while (val) {
        num = br.readLine();
        try {
            Integer numVal = Integer.parseInt((String) num);
            if (numVal instanceof Integer) {
                val = false;
                num = numVal;
            }
        } catch (Exception e) {
            System.out.println("Error. Please input a valid number :-");
        }
    }
    return ((Integer) num).intValue();
}
于 2015-03-17T04:37:54.830 に答える
0

これは、質問8391979「Javaには不正なデータの例外をスローしないint.tryparseがありますか?[重複]」に対する回答です。この質問は閉じられ、この質問にリンクされています。

2016年8月17日編集:ltrimZeroesメソッドを追加し、tryParse()で呼び出しました。numberStringに先行ゼロがないと、誤った結果が生じる可能性があります(コードのコメントを参照)。正と負の「数値」に対して機能するpublicstaticString ltrimZeroes(String numberString)メソッドもあります(END Edit)

以下に、文字列自体を解析し、JavaのInteger.parseInt(String s)よりも少し高速な高速最適化tryParse()メソッド(C#と同様)を使用したintの基本的なWrapper(ボクシング)クラスを示します。

public class IntBoxSimple {
    // IntBoxSimple - Rudimentary class to implement a C#-like tryParse() method for int
    // A full blown IntBox class implementation can be found in my Github project
    // Copyright (c) 2016, Peter Sulzer, Fürth
    // Program is published under the GNU General Public License (GPL) Version 1 or newer

    protected int _n; // this "boxes" the int value

    // BEGIN The following statements are only executed at the
    // first instantiation of an IntBox (i. e. only once) or
    // already compiled into the code at compile time:
    public static final int MAX_INT_LEN =
            String.valueOf(Integer.MAX_VALUE).length();
    public static final int MIN_INT_LEN =
            String.valueOf(Integer.MIN_VALUE).length();
    public static final int MAX_INT_LASTDEC =
            Integer.parseInt(String.valueOf(Integer.MAX_VALUE).substring(1));
    public static final int MAX_INT_FIRSTDIGIT =
            Integer.parseInt(String.valueOf(Integer.MAX_VALUE).substring(0, 1));
    public static final int MIN_INT_LASTDEC =
            -Integer.parseInt(String.valueOf(Integer.MIN_VALUE).substring(2));
    public static final int MIN_INT_FIRSTDIGIT =
            Integer.parseInt(String.valueOf(Integer.MIN_VALUE).substring(1,2));
    // END The following statements...

    // ltrimZeroes() methods added 2016 08 16 (are required by tryParse() methods)
    public static String ltrimZeroes(String s) {
        if (s.charAt(0) == '-')
            return ltrimZeroesNegative(s);
        else
            return ltrimZeroesPositive(s);
    }
    protected static String ltrimZeroesNegative(String s) {
        int i=1;
        for ( ; s.charAt(i) == '0'; i++);
        return ("-"+s.substring(i));
    }
    protected static String ltrimZeroesPositive(String s) {
        int i=0;
        for ( ; s.charAt(i) == '0'; i++);
        return (s.substring(i));
    }

    public static boolean tryParse(String s,IntBoxSimple intBox) {
        if (intBox == null)
            // intBoxSimple=new IntBoxSimple(); // This doesn't work, as
            // intBoxSimple itself is passed by value and cannot changed
            // for the caller. I. e. "out"-arguments of C# cannot be simulated in Java.
            return false; // so we simply return false
        s=s.trim(); // leading and trailing whitespace is allowed for String s
        int len=s.length();
        int rslt=0, d, dfirst=0, i, j;
        char c=s.charAt(0);
        if (c == '-') {
            if (len > MIN_INT_LEN) { // corrected (added) 2016 08 17
                s = ltrimZeroesNegative(s);
                len = s.length();
            }
            if (len >= MIN_INT_LEN) {
                c = s.charAt(1);
                if (!Character.isDigit(c))
                    return false;
                dfirst = c-'0';
                if (len > MIN_INT_LEN || dfirst > MIN_INT_FIRSTDIGIT)
                    return false;
            }
            for (i = len - 1, j = 1; i >= 2; --i, j *= 10) {
                c = s.charAt(i);
                if (!Character.isDigit(c))
                    return false;
                rslt -= (c-'0')*j;
            }
            if (len < MIN_INT_LEN) {
                c = s.charAt(i);
                if (!Character.isDigit(c))
                    return false;
                rslt -= (c-'0')*j;
            } else {
                if (dfirst >= MIN_INT_FIRSTDIGIT && rslt < MIN_INT_LASTDEC)
                    return false;
                rslt -= dfirst * j;
            }
        } else {
            if (len > MAX_INT_LEN) { // corrected (added) 2016 08 16
                s = ltrimZeroesPositive(s);
                len=s.length();
            }
            if (len >= MAX_INT_LEN) {
                c = s.charAt(0);
                if (!Character.isDigit(c))
                    return false;
                dfirst = c-'0';
                if (len > MAX_INT_LEN || dfirst > MAX_INT_FIRSTDIGIT)
                    return false;
            }
            for (i = len - 1, j = 1; i >= 1; --i, j *= 10) {
                c = s.charAt(i);
                if (!Character.isDigit(c))
                    return false;
                rslt += (c-'0')*j;
            }
            if (len < MAX_INT_LEN) {
                c = s.charAt(i);
                if (!Character.isDigit(c))
                    return false;
                rslt += (c-'0')*j;
            }
            if (dfirst >= MAX_INT_FIRSTDIGIT && rslt > MAX_INT_LASTDEC)
                return false;
            rslt += dfirst*j;
        }
        intBox._n=rslt;
        return true;
    }

    // Get the value stored in an IntBoxSimple:
    public int get_n() {
        return _n;
    }
    public int v() { // alternative shorter version, v for "value"
        return _n;
    }
    // Make objects of IntBoxSimple (needed as constructors are not public):
    public static IntBoxSimple makeIntBoxSimple() {
        return new IntBoxSimple();
    }
    public static IntBoxSimple makeIntBoxSimple(int integerNumber) {
        return new IntBoxSimple(integerNumber);
    }

    // constructors are not public(!=:
    protected IntBoxSimple() {} {
        _n=0; // default value an IntBoxSimple holds
    }
    protected IntBoxSimple(int integerNumber) {
        _n=integerNumber;
    }
}

クラスIntBoxSimpleのテスト/サンプルプログラム:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class IntBoxSimpleTest {
    public static void main (String args[]) {
        IntBoxSimple ibs = IntBoxSimple.makeIntBoxSimple();
        String in = null;
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        do {
            System.out.printf(
                    "Enter an integer number in the range %d to %d:%n",
                        Integer.MIN_VALUE, Integer.MAX_VALUE);
            try { in = br.readLine(); } catch (IOException ex) {}
        } while(! IntBoxSimple.tryParse(in, ibs));
        System.out.printf("The number you have entered was: %d%n", ibs.v());
    }
}
于 2016-08-16T11:08:36.473 に答える
0

正規表現とデフォルトのパラメーター引数を試してください

public static int parseIntWithDefault(String str, int defaultInt) {
    return str.matches("-?\\d+") ? Integer.parseInt(str) : defaultInt;
}


int testId = parseIntWithDefault("1001", 0);
System.out.print(testId); // 1001

int testId = parseIntWithDefault("test1001", 0);
System.out.print(testId); // 1001

int testId = parseIntWithDefault("-1001", 0);
System.out.print(testId); // -1001

int testId = parseIntWithDefault("test", 0);
System.out.print(testId); // 0

apache.commons.lang3を使用している場合は、NumberUtilsを使用します

int testId = NumberUtils.toInt("test", 0);
System.out.print(testId); // 0
于 2017-08-03T11:28:53.313 に答える
0

特に整数を要求する場合に機能する別の提案を投入したいと思います。単にlongを使用し、エラーの場合はLong.MIN_VALUEを使用します。これは、Reader.read()がcharの範囲の整数を返す、またはリーダーが空の場合は-1を返す、Readerのcharに使用されるアプローチに似ています。

FloatとDoubleの場合、NaNは同様の方法で使用できます。

public static long parseInteger(String s) {
    try {
        return Integer.parseInt(s);
    } catch (NumberFormatException e) {
        return Long.MIN_VALUE;
    }
}


// ...
long l = parseInteger("ABC");
if (l == Long.MIN_VALUE) {
    // ... error
} else {
    int i = (int) l;
}
于 2018-02-15T14:35:06.130 に答える
0

Integer.parseInt既存の回答を考慮して、私は仕事をするためのソースコードをコピーして貼り付け、拡張しました、そして私の解決策

  • ( Lang 3 NumberUtilsとは異なり)潜在的に遅いtry-catchを使用しません。
  • あまりにも大きな数をキャッチできない正規表現を使用しません、
  • ボクシングを避けます(グアバとは異なりますInts.tryParse())、
  • 割り当ては必要ありません(、、とは異なりint[]ます)BoxOptionalInt
  • CharSequence全体ではなく、その一部または一部をString受け入れます。
  • できる任意の基数を使用できますInteger.parseInt。つまり、[2,36]、
  • ライブラリに依存しません。

toIntOfDefault("-1", -1)唯一の欠点は、との間に違いがないことtoIntOrDefault("oops", -1)です。

public static int toIntOrDefault(CharSequence s, int def) {
    return toIntOrDefault0(s, 0, s.length(), 10, def);
}
public static int toIntOrDefault(CharSequence s, int def, int radix) {
    radixCheck(radix);
    return toIntOrDefault0(s, 0, s.length(), radix, def);
}
public static int toIntOrDefault(CharSequence s, int start, int endExclusive, int def) {
    boundsCheck(start, endExclusive, s.length());
    return toIntOrDefault0(s, start, endExclusive, 10, def);
}
public static int toIntOrDefault(CharSequence s, int start, int endExclusive, int radix, int def) {
    radixCheck(radix);
    boundsCheck(start, endExclusive, s.length());
    return toIntOrDefault0(s, start, endExclusive, radix, def);
}
private static int toIntOrDefault0(CharSequence s, int start, int endExclusive, int radix, int def) {
    if (start == endExclusive) return def; // empty

    boolean negative = false;
    int limit = -Integer.MAX_VALUE;

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

        start++;
        // Cannot have lone "+" or "-"
        if (start == endExclusive) return def;
    }
    int multmin = limit / radix;
    int result = 0;
    while (start < endExclusive) {
        // Accumulating negatively avoids surprises near MAX_VALUE
        int digit = Character.digit(s.charAt(start++), radix);
        if (digit < 0 || result < multmin) return def;
        result *= radix;
        if (result < limit + digit) return def;
        result -= digit;
    }
    return negative ? result : -result;
}
private static void radixCheck(int radix) {
    if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)
        throw new NumberFormatException(
                "radix=" + radix + " ∉ [" +  Character.MIN_RADIX + "," + Character.MAX_RADIX + "]");
}
private static void boundsCheck(int start, int endExclusive, int len) {
    if (start < 0 || start > len || start > endExclusive)
        throw new IndexOutOfBoundsException("start=" + start + " ∉ [0, min(" + len + ", " + endExclusive + ")]");
    if (endExclusive > len)
        throw new IndexOutOfBoundsException("endExclusive=" + endExclusive + " > s.length=" + len);
}
于 2020-04-16T23:20:27.590 に答える
0

これはかなり古い質問であることを私は知っていますが、私はその問題を解決するための最新の解決策を探していました。

私は次の解決策を思いついた:

public static OptionalInt tryParseInt(String string) {
    try {
        return OptionalInt.of(Integer.parseInt(string));
    } catch (NumberFormatException e) {
        return OptionalInt.empty();
    }
}

使用法:

@Test
public void testTryParseIntPositive() {
    // given
    int expected = 5;
    String value = "" + expected;

    // when
    OptionalInt optionalInt = tryParseInt(value);

    // then
    Assert.assertTrue(optionalInt.isPresent());
    Assert.assertEquals(expected, optionalInt.getAsInt());
}

@Test
public void testTryParseIntNegative() {
    // given
    int expected = 5;
    String value = "x" + expected;

    // when
    OptionalInt optionalInt = tryParseInt(value);

    // then
    Assert.assertTrue(optionalInt.isEmpty());
}
于 2022-01-04T09:25:22.320 に答える
-1

次のようにNullオブジェクトを使用できます。

public class Convert {

    @SuppressWarnings({"UnnecessaryBoxing"})
    public static final Integer NULL = new Integer(0);

    public static Integer convert(String integer) {

        try {
            return Integer.valueOf(integer);
        } catch (NumberFormatException e) {
            return NULL;
        }

    }

    public static void main(String[] args) {

        Integer a = convert("123");
        System.out.println("a.equals(123) = " + a.equals(123));
        System.out.println("a == NULL " + (a == NULL));

        Integer b = convert("onetwothree");
        System.out.println("b.equals(123) = " + b.equals(123));
        System.out.println("b == NULL " + (b == NULL));

        Integer c = convert("0");
        System.out.println("equals(0) = " + c.equals(0));
        System.out.println("c == NULL " + (c == NULL));

    }

}

この例のmainの結果は次のとおりです。

a.equals(123) = true
a == NULL false
b.equals(123) = false
b == NULL true
c.equals(0) = true
c == NULL false

このようにして、失敗した変換をいつでもテストできますが、結果は整数インスタンスとして処理されます。NULLが表す数値(≠0)を微調整することもできます。

于 2009-09-28T09:17:05.463 に答える
-1

自分でロールすることもできますが、commonslangのStringUtils.isNumeric() メソッドを使用するのも同じくらい簡単です。Character.isDigit()を使用して、文字列内の各文字を反復処理します。

于 2011-12-05T21:29:37.783 に答える
-1

値を検証するために例外を使用しないでください

単一文字の場合、簡単な解決策があります。

Character.isDigit()

値が長い場合は、いくつかのutilsを使用することをお勧めします。Apacheによって提供されるNumberUtilsは、ここで完全に機能します。

NumberUtils.isNumber()

https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/math/NumberUtils.htmlを確認してください

于 2018-03-28T22:31:43.203 に答える