簡體   English   中英

字符串到 Java 中的 32 位整數,默認值比異常

[英]String to 32 bit Integer in Java, with default value than exception

我有一串有符號整數值,范圍從“+2147483650”到“-9638527412”。 我需要將它們解析為 32 位整數,這樣,當字符串值高於整數容量 (2^31) 時,它應該返回最接近的可能整數值。 使用“Integer.parseInt”會給出越界異常。

例子:

input: "+2147483650"
output: "+2147483647"
input: ""-963852741258"
output: "-2147483648"

我試圖使用現有的功能,但我被困在這里。


try{
    //num =Integer.valueOf(stringNumber);
    num =Integer.parseInt(stringNumber);
}catch(Exception e){
    num = -2147483648; // if stringNumber is negative
    num = +2147483647 // if stringNumber is positive
}
  

  

由於您的值范圍僅限於"+2147483650""-9638527412" ,您可以解析為long並檢查是否溢出。

public static int parse(String stringNumber) {
    long value = Long.parseLong(stringNumber);
    return (value < Integer.MIN_VALUE ? Integer.MIN_VALUE :
            value > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) value);
}

測試

System.out.println(parse("+2147483650"));
System.out.println(parse("42"));
System.out.println(parse("-9638527412"));

輸出

2147483647
42
-2147483648

如果沒有理由不能使用更大的數據類型,例如Long那么您可以將其解析為Long 如果解析失敗,它將拋出NumberFormatException

try {
    long tmp = Long.parseLong(stringNumber);

    int result;
    if (tmp < Integer.MIN_VALUE) {
        result = Integer.MIN_VALUE;
    } else if (tmp > Integer.MAX_VALUE) {
        result = Integer.MAX_VALUE;
    } else {
        // safe cast to int (java 8)
        result = Math.toIntExact(tmp);
    }
    // TODO do something with the result
} catch (NumberFormatException e) {
    // could not parse
}

給定指定的潛在輸入范圍,此函數會將給定的字符串限制在[Integer.MIN_VALUE, Integer.MAX_VALUE]范圍內:

static int clampedStringValue(String s) {
        long n = Long.parseLong(s);
        if (n > Integer.MAX_VALUE) {
                return Integer.MAX_VALUE;
        } else if (n < Integer.MIN_VALUE) {
                return Integer.MIN_VALUE;
        } else {
                return (int)n;
        }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM