有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如果用户输入的“数字”超过了用于解释该数字的内存大小,那么正确的测试方法是什么?

我不愿意重新发明这辆自行车,我希望被证明是解决这个问题的行之有效的方法

我通过一些字符串接口(例如文本输入)从用户那里收集数值

我想确保,无论我用于收集此信息的内存空间是什么类型,我都不允许用户输入超过此值的数字

我的直觉告诉我,唯一的方法就是测量最大值的字符串长度。。。比如

if( (userInput + "").length() > (Integer.MAX_VALUE + "").length()){
   //user has entered too many digits for an Integer to hold.
}

但我觉得这很难看,我想有一个更干净的方法来处理这个问题


共 (3) 个答案

  1. # 1 楼答案

    您也可以尝试以下方法来获取位信息:

    BigInteger userInputCheck=new BigInteger(userInput);
    
    if(userInputCheck.bitLength()>31){
          //error : cannot convert the input to primitive int type
    }
    

    编辑

    如果您使用的是Apache Commons,NumberUtils实用程序类中有一个方法^{}

    从文件中:

        ...it starts trying to create successively larger types from the type specified 
    until one is found that can represent the value...
    

    Source Code for the above method

  2. # 2 楼答案

    当您第一次获得userInput时,您应该验证用户输入的内容是否有效,如果有效,则验证Integer。parseInt()将起作用。如果无效,即大于整数的值。最大值,它将引发异常

    您描述的行为导致使用catch作为流控制,这不是一个好的设计

    坏的:

    try{
        Integer.parseInt(max);
        //do something with the integer
    }catch (NumberFormatException e)
    {
        //user has entered too many digits for an Integer to hold.
        userInput = Integer.MAX_VALUE + "";
    }
    
  3. # 3 楼答案

    如果用户输入超出范围或不是真正的整数,Integer的构造函数将通过抛出一个NumberFormatException来检测这一点。请参见以下测试程序示例:

    public class UserInputBigInteger {
    
        public static void main(String[] args) {
            String[] inputStrings = {
                    String.valueOf(Integer.MAX_VALUE)
                    , String.valueOf(Integer.MAX_VALUE)+"0" // x10
                    , String.valueOf(Integer.MAX_VALUE)+"a" // not an integer
            };
    
            for (String inputString : inputStrings) {
                try {
                    Integer inputInteger = new Integer(inputString);
                    final int MAX = Integer.MAX_VALUE;
                    System.out.format("userInput %s is within range %,d%n"
                            , inputString, MAX);
                } catch (NumberFormatException ex) {
                    System.out.format("userInput does not appear to be valid interger: %s%n"
                            , ex.getMessage());     }
            }
        }
    
    }
    

    产出将是:

    userInput 2147483647 is within range 2,147,483,647
    userInput does not appear to be an interger: For input string: "21474836470"
    userInput does not appear to be an interger: For input string: "2147483647a"