102

我有一个项目,我们经常在其中Integer.parseInt()将 String 转换为 int。当出现问题时(例如,String不是数字而是字母a,或其他),此方法将引发异常。但是,如果我必须在任何地方处理我的代码中的异常,这很快就会变得非常难看。我想把它放在一个方法中,但是,我不知道如何返回一个干净的值以表明转换出错了。

在 C++ 中,我可以创建一个接受指向 int 的指针并让方法本身返回 true 或 false 的方法。但是,据我所知,这在 Java 中是不可能的。我还可以创建一个包含真/假变量和转换值的对象,但这似乎也不理想。全局值也是如此,这可能会给我的多线程带来一些麻烦。

那么有没有一种干净的方法来做到这一点?

4

26 回答 26

153

您可以返回 anInteger而不是,在解析失败int时返回。null

遗憾的是,Java 没有提供一种在内部没有抛出异常的情况下执行此操作的方法 - 您可以隐藏异常(通过捕获它并返回 null),但如果您解析数百个异常,它仍然可能是一个性能问题数千位用户提供的数据。

编辑:这种方法的代码:

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

text请注意,如果为空,我不确定这会做什么。您应该考虑到 - 如果它代表一个错误(即您的代码很可能传递一个无效值,但绝不应该传递 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 Lang 3 NumberUtils处理缺失输入的默认值。

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

There is Ints.tryParse() in Guava. It doesn't throw exception on non-numeric string, however it does throw exception on null string.

于 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”,但这或多或少是用 null 检查替换了 try/catch 构造。如果您“忘记”错误处理,则行为会略有不同:如果您没有捕获异常,则没有赋值,并且左侧变量保持旧值。如果您不测试 null,您可能会受到 JVM (NPE) 的影响。

打哈欠的建议对我来说看起来更优雅,因为我不喜欢返回 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如果一切顺利并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

派生 parseInt方法怎么样?

这很简单,只需将内容复制粘贴到一个新的实用程序,该实用程序返回IntegerOptional<Integer>用返回替换 throws。底层代码似乎没有异常,但最好检查一下

通过跳过整个异常处理内容,您可以在无效输入上节省一些时间。该方法从 JDK 1.0 开始就存在,因此您不太可能需要做很多事情来使其保持最新状态。

于 2016-09-12T16:11:08.450 回答
1

如果您使用的是 Java 8 或更高版本,则可以使用我刚刚发布的库:https ://github.com/robtimus/try-parse 。它支持不依赖于捕获异常的 int、long 和 boolean。与 Guava 的 Ints.tryParse 不同,它返回 OptionalInt / OptionalLong / Optional,就像在https://stackoverflow.com/a/38451745/1180351中一样,但效率更高。

于 2019-04-28T11:53:45.403 回答
1

也许有人正在寻找更通用的方法,因为 Java 8 有java.util.function允许定义供应商函数的包。您可以有一个接受供应商和默认值的函数,如下所示:

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 回答
1

Jon Skeet 给出的答案很好,但我不喜欢返回nullInteger 对象。我发现这使用起来很混乱。由于 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 回答
0

我建议你考虑一种方法

 IntegerUtilities.isValidInteger(String s)

然后按照您认为合适的方式实施。如果您希望将结果带回 - 可能是因为您无论如何都使用 Integer.parseInt() - 您可以使用数组技巧。

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

您将 result[0] 设置为过程中找到的整数值。

于 2009-09-28T11:46:31.363 回答
0

They way I handle this problem is recursively. For example when reading data from the console:

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

这有点类似于 Nikolay 的解决方案:

 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 方法演示了代码。实现 Parser 接口的另一种方法显然是从构造中设置“\D+”,并且让方法什么都不做。

于 2009-09-28T14:30:58.660 回答
0

为避免异常,您可以使用 Java 的Format.parseObject方法。下面的代码基本上是 Apache Common 的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

如果有人特别要求整数,我想提出另一个可行的建议:只需使用 long 并使用 Long.MIN_VALUE 处理错误情况。这类似于 Reader 中用于字符的方法,其中 Reader.read() 返回字符范围内的整数,如果读取器为空,则返回 -1。

对于 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

我知道这是一个相当古老的问题,但我一直在寻找解决该问题的现代解决方案。

我想出了以下解决方案:

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 回答
0

考虑到现有的答案,我复制粘贴并增强了源代码Integer.parseInt来完成这项工作,以及我的解决方案

  • 不使用可能很慢的 try-catch(与Lang 3 NumberUtils不同),
  • 不使用无法捕获太大数字的正则表达式,
  • 避免拳击(不像番石榴Ints.tryParse()),
  • 不需要任何分配(与int[], Box,不同OptionalInt),
  • 接受它的任何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 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

这是对问题 8391979“Does java has a int.tryparse that doesn't throw an exception for bad data?[duplicate]”的回答,该问题已关闭并链接到此问题。

编辑 2016 08 17:添加 ltrimZeroes 方法并在 tryParse() 中调用它们。在 numberString 中没有前导零可能会给出错误的结果(参见代码中的注释)。现在还有公共静态 String ltrimZeroes(String numberString) 方法,适用于正数和负数“数字”(END编辑)

下面你会发现一个用于 int 的基本 Wrapper(装箱)类,它具有高速优化的 tryParse() 方法(类似于 C# 中的方法),它解析字符串本身并且比 Java 中的 Integer.parseInt(String s) 快一点:

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 回答
-1

您可以像这样使用 Null-Object:

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

这样,您始终可以测试失败的转换,但仍将结果作为 Integer 实例使用。您可能还想调整NULL表示的数字 (≠ 0)。

于 2009-09-28T09:17:05.463 回答
-1

可以自己滚动,但使用 commons lang 的StringUtils.isNumeric() 方法同样容易。它使用Character.isDigit()迭代字符串中的每个字符。

于 2011-12-05T21:29:37.783 回答
-1

您不应该使用 Exceptions 来验证您的值

对于单个字符,有一个简单的解决方案:

Character.isDigit()

对于更长的值,最好使用一些实用程序。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 回答