栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

在Java中将字符串转换为整数时如何检测溢出

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在Java中将字符串转换为整数时如何检测溢出

如果我想在Java中将字符串转换为int,您是否知道我是否可以检测到溢出?

是。捕获解析异常将是正确的方法,但是这里的困难在于,对 任何 解析错误(包括溢出)都

Integer.parseInt(Strings)
抛出a
。您可以通过查看JDK 文件中的Java源代码进行验证。幸运的是,由于s没有界限,所以存在一个构造器将抛出相同的解析异常, 范围限制 除外
。我们可以使用此知识来捕获溢出情况:
NumberFormatException
src.zip
BigInteger(Strings)


BigInteger


int parseIntWithOverflow(String s) throws Exception {    int result = 0;    try {        result = Integer.parseInt(s);    } catch (Exception e) {        try { new BigInteger(s);        } catch (Exception e1) { throw e; // re-throw, this was a formatting problem        }        // We're here iff s represents a valid integer that's outside        // of java.lang.Integer range. Consider using custom exception type.        throw new NumberFormatException("Input is outside of Integer range!");    }    // the input parsed no problem    return result;}

如果你真的需要自定义此为
超过Integer.MAX_VALUE的输入,你可以这样做只是抛出自定义异常,通过使用@谢尔盖的建议之前。如果上述方法过于矫kill过正,并且您无需隔离溢出情况,只需通过捕获它来抑制异常:

int result = 0;try {    result = Integer.parseInt(s);} catch (NumberFormatException e) {    // act accordingly}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/570688.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号