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);
     




  • 相关阅读:
    如何完成域名和ip地址的绑定
    如何把域名解析到网站空间IP上?
    网站和数据库分开放,可以实现吗
    访问网站出现 Directory Listing Denied This Virtual Directory
    访问网站出现 Directory Listing Denied This Virtual Directory
    免费空间上的mysql数据库怎么连接?
    我不是你的菜
    很奇怪木瓜移动一上就火了
    敏捷产业
    前端开发工具
  • 原文地址:https://www.cnblogs.com/sagech/p/4527387.html
Copyright © 2011-2022 走看看