zoukankan      html  css  js  c++  java
  • java.lang.IllegalArgumentException: n must be positive

    public static String  randomKey(){
    		Random random = new Random();
    		int key = random.nextInt(((int)System.currentTimeMillis()));
    		return String.valueOf(key);
    	}
    

      直接调用方法,发生异常:

    Exception in thread "main" java.lang.IllegalArgumentException: n must be positive
        at java.util.Random.nextInt(Random.java:300)
        at com.stresstest.example.RandomTest.randomKey(RandomTest.java:24)
        at com.stresstest.example.RandomTest.main(RandomTest.java:15)

    异常说明:

    java.lang.IllegalArgumentException: n must be positive
    参数异常,n必须是一个整数,显然(int)System.currentTimeMillis()产生的值不是一个正数。

    分析:
      系统产生的异常,测试时系统正常,上线之后某一天之后产生了异常。
    查看System.currentTimeMillis()产生了问题,产生异常时间是2015-05-23当天开始往后,一直报错。之前就没事

    时间:2015-05-23
    测试结果:正常
    System.currentTimeMillis():1432350368523
    (int)System.currentTimeMillis():2126349176
    randomKey():1369912950
    时间:2015-05-24
    测试结果:
    1432436706512
    -2082194224 Exception in thread "main" java.lang.IllegalArgumentException: n must be positive at java.util.Random.nextInt(Random.java:300) at com.stresstest.example.RandomTest.randomKey(RandomTest.java:24) at com.stresstest.example.RandomTest.main(RandomTest.java:15)
    
    

      因此可以知道结果,阴性问题,值得注意,至于long型转换为int型出现问题在这里不做深究,有这个问题深层研究的请补充。

    解决办法:

    int key = random.nextInt(((int)System.currentTimeMillis()));
    修改为:
      1.random.nextInt(((int)System.currentTimeMillis()/1000));
      2.random.nextInt(999999999);
     




  • 相关阅读:
    Docker跨平台架构的新特性buildx的启用方式
    Linux 如何安装rvm和ruby
    Linux
    ubuntu安装 vmware workstation pro 15.1.1
    docker-compose搭建golang本地开发环境
    linux 常用命令
    leetcode 1046 最后一块石头的重量
    leetcode 330 按要求补齐数组
    MySQL 字符集与比较规则
    Python 是什么语言
  • 原文地址:https://www.cnblogs.com/sagech/p/4527387.html
Copyright © 2011-2022 走看看