Integer.decode("-011")

Integer.decode("-011")


public static Integer decode(String nm) throws NumberFormatException
将 String 解码为 Integer。接受通过以下语法给出的十进制、十六进制和八进制数字: 
DecodableString: 
Signopt DecimalNumeral 
Signopt 0x HexDigits 
Signopt 0X HexDigits 
Signopt # HexDigits 
Signopt 0 OctalDigits 


跟在(可选)负号和/或基数说明符(“0x”、“0X”、“#”或前导零)后面的字符序列是使用指示的基数(10、16 或 8)通过 Integer.parseInt 方法解析的。字符序列必须表示一个正值,否则会抛出 NumberFormatException。如果指定的 String 的第一个字符是减号,则对结果求反。String 中不允许出现空白字符。






    public static Integer decode(String nm) throws NumberFormatException {
        int radix = 10;
        int index = 0;
        boolean negative = false;
        Integer result;


        // Handle minus sign, if present
        if (nm.startsWith("-")) {
            negative = true;
            index++;
        }


        // Handle radix specifier, if present
if (nm.startsWith("0x", index) || nm.startsWith("0X", index)) {
   index += 2;
            radix = 16;
}
else if (nm.startsWith("#", index)) {
   index ++;
            radix = 16;
}
else if (nm.startsWith("0", index) && nm.length() > 1 + index) {
   index ++;
            radix = 8;
}


        if (nm.startsWith("-", index))
            throw new NumberFormatException("Negative sign in wrong position");


        try {
            result = Integer.valueOf(nm.substring(index), radix);
            result = negative ? Integer.valueOf(-result.intValue()) : result;
        } catch (NumberFormatException e) {
            // If number is Integer.MIN_VALUE, we'll end up here. The next line
            // handles this case, and causes any genuine format error to be
            // rethrown.
            String constant = negative ? "-" + nm.substring(index)
                                       : nm.substring(index);
            result = Integer.valueOf(constant, radix);
        }
        return result;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值