在Java中获取给定范围之间的随机数

时间:2016-01-26 14:38:39

标签: java random range

如果最小值大于1,如何在Java中获取给定范围之间的随机数?例如,如果我想获得6到20之间的随机数。目前我正在使用此代码

Random rand = new Random(); 
int  rnd = rand.nextInt(499) + 1;

它运行良好,但如果我将1更改为某个高数字(例如6),它将无法正常工作,我想得到6到20之间的随机数。是否可以使用上述函数?

1 个答案:

答案 0 :(得分:2)

只需计算0到14之间的随机数,然后加上6

 org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in ServletContext resource [/WEB-INF/classes/connectionConf.xml]: Invocation of init method failed; nested exception is org.hibernate.metamodel.source.MappingException: Error accessing stax stream
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:521)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
        at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:293)
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:290)
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:191)
        at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1117)....