如何使用java Random.nextInt()方法

  介绍

这篇文章主要为大家展示了如何使用java Random.nextInt()方法,内容简而易懂,希望大家可以学习一下,学习完之后肯定会有收获的,下面让小编带大家一起来看看吧。

lic int nextInt (int n)

该方法的作用是生成一个随机的int值,该值介于[0,n)的区间,也就是0到n之间的随机int值,包含0而不包含n。

直接上代码:

包org.xiaowu.random.demo;
  
  进口java.util.Random;
  
  进口org.junit.Test;
  
  公开课RandomDemo {
  
  @Test
  公共空间演示(){
  随机rnd=new随机();
  int代码=rnd.nextInt (8999) + 1000;
  System.out.println(“代码:“+代码);
  }
  
  
  @Test
  公共空间Demo1 () {
  随机r=新的随机();
  int nextInt=r.nextInt ();
  随机r1=新的随机(10);
  int nextInt2=r1.nextInt ();
  System.out.println (“nextInt:“+ nextInt);
  System.out.println (“nextInt2:“+ nextInt2);
  }/* *
  *生成[0,1.0)区间的小数
  *
  */@Test
  公共空间以及接下来(){
  随机r=新的随机();
  双d1=r.nextDouble ();
  System.out.println (“d1:“+ d1);
  }/* *
  *生成[0,5.0)区间的小数
  *
  */@Test
  公共空间Demo3 () {
  随机r=新的随机();
  双d2=r.nextDouble () * 5;
  System.out.println (“d1:“+ d2);
  }/* *
  *生成[1,2.5)区间的小数
  *
  */@Test
  公共空间Demo4 () {
  随机r=新的随机();
  双d3=r.nextDouble () * 1.5 + 1;
  System.out.println (“d1:“+ d3);
  }/* *
  *生成任意整数
  *
  */@Test
  公共空间Demo5 () {
  随机r=新的随机();
  int n1=r.nextInt ();
  System.out.println (“d1:“+ n1);
  }/* *
  *生成[0,10)区间的整数
  *
  */@Test
  公共空间Demo6 () {
  随机r=新的随机();
  int n2=r.nextInt (10);
  int n3=Math.abs (r.nextInt () % 10);
  System.out.println (“n2:“+ n2);
  System.out.println (“n3:“+ n3);
  }/* *
  *生成[0,10]区间的整数
  *
  */@Test
  公共空间Demo7 () {
  随机r=新的随机();
  int n3=r.nextInt (11);
  int陶瓷=Math.abs (r.nextInt () % 11);
  System.out.println (“n3:“+ n3);
  System.out.println(“陶瓷:“+陶瓷);
  }/* *
  *生成[3,15)区间的整数
  *
  */@Test
  公共空间Demo8 () {
  随机r=新的随机();
  int陶瓷=r.nextInt (18) - 3;
  int它们=Math.abs (r.nextInt () % 18) - 3;
  System.out.println(“陶瓷:“+陶瓷);
  System.out.println(“;它们:“+它们);
  }
  
  }


问题

今天想让程序返回一个区间内的随机数。忘记怎么写了,就去百度搜给出的结果并不对。

进口java.util.Random;/* *
  * @author惠普
  * @date 2019/4/16
  */公开课randomTest {
  公共静态void main (String [] args) {
  
  随机随机=new随机();//生成64 - 128内的随机数
  int i=random.nextInt () * (128 - 64 + 1) + 64;/* *
  *生成(m, n)的数字
  * int i1=random.nextInt () * (n - m + 1) + m;
  * *///生成0 - 64内的数字
  int i1=random.nextInt () * (64 - 0 + 1);/* *
  *生成低氮之内的数字
  * int i1=random.nextInt () * (n-0 + 1);
  *
  *
  * */}
  }

这样是不对的,我就去查看API文档,发现nextInt()可以有参数也可以无参数。

无参数的方法直接调用返回的是一个很大的正负区间上的数。

如果想返回想要的范围内的数,应该:

包chapter6;
  
  进口java.util.Random;
  
  进口org.omg.Messaging.SyncScopeHelper;
  
  公开课RandomTest {
  公共静态void main (String [] args) {
  随机随机=new随机();
  for (int i=0; i<200;我+ +)
  {//输出为0 ~ 13之间的整数
  System.out.println (random.nextInt (14));
  }
  System.out.println (“- - - - - - - - - - - - - - - - - - - - - - - - - - - - -“);
  (int j=0; j<100; j + +) {//输出为9 ~ 0之间的整数
  System.out.println (random.nextInt (10) 9);
  }
  }
  }

以上就是关于如何使用java Random.nextInt()方法的内容,如果你们有学习到知识或者技能,可以把它分享出去让更多的人看的到。

如何使用java Random.nextInt()方法