java如果用户输入的“数字”超过了用于解释该数字的内存大小,那么正确的测试方法是什么?
我不愿意重新发明这辆自行车,我希望被证明是解决这个问题的行之有效的方法
我通过一些字符串接口(例如文本输入)从用户那里收集数值
我想确保,无论我用于收集此信息的内存空间是什么类型,我都不允许用户输入超过此值的数字
我的直觉告诉我,唯一的方法就是测量最大值的字符串长度。。。比如
if( (userInput + "").length() > (Integer.MAX_VALUE + "").length()){
//user has entered too many digits for an Integer to hold.
}
但我觉得这很难看,我想有一个更干净的方法来处理这个问题
# 1 楼答案
您也可以尝试以下方法来获取位信息:
编辑
如果您使用的是Apache Commons,}
NumberUtils
实用程序类中有一个方法^{从文件中:
Source Code for the above method
# 2 楼答案
当您第一次获得userInput时,您应该验证用户输入的内容是否有效,如果有效,则验证Integer。parseInt()将起作用。如果无效,即大于整数的值。最大值,它将引发异常
您描述的行为导致使用catch作为流控制,这不是一个好的设计
坏的:
# 3 楼答案
如果用户输入超出范围或不是真正的整数,
Integer
的构造函数将通过抛出一个NumberFormatException
来检测这一点。请参见以下测试程序示例:产出将是: