赞
踩
利用Random类来产生5个20~ 50之间的随机整数。
提示: Random.nextInt(方法的作用是生成一个随机的int值 ,该值介于[0,n)的区间,也就是0到n之间的随机int值,包含0而不包含n。
方法1:int nextInt(int n)
- import java. util. Random;
-
- public class Example1 {
-
- public static void main(String[] args) {
-
- Random random=new Random( );
-
- for(int i=0; i<5; i++) {
-
- int num=20+random.nextInt(31);
-
- System.out. println(num);
-
- }
-
- }
-
- }
方法2: double next Double()
- import java.util.Random;
-
- public class Example {
-
- public static void main(String[] args)throws IllegalArgumentException{
-
- for(int i=0; i<5; i++) {
- System.out.println(getRandomNumberInRange(20,50));
-
- }
-
- }
-
- private static int getRandomNumberInRange(int min,int max)throws IllegalArgumentException{
-
- if(min>=max) {
-
- throw new IllegalArgumentException("max must be greater than min");
-
- }
-
- Random random=new Random();
-
- return (int)(random.nextDouble()*(max-min)+1)+min;
-
- }
-
- }
其它:
- import java. util. Random;
-
- public class Example1 {
-
- public static void main(String[] args) {
-
- Random random=new Random( );
-
- for(int i=0; i<5; i++) {
-
- double num=20+31*random.nextDouble();
-
- System.out. println((int)num);
-
- }
-
- }
-
- }
方法3:Math. random()
- import java.util.Random;
-
- public class Example {
-
- public static void main(String[] args)throws IllegalArgumentException{
-
- for(int i=0; i<5; i++) {
- System.out.println(getRandomNumberInRange(20,50));
-
- }
-
- }
-
- private static int getRandomNumberInRange(int min,int max)throws IllegalArgumentException{
-
- if(min>=max) {
-
- throw new IllegalArgumentException("max must be greater than min");
-
- }
-
- // Random random=new Random();
-
- return (int)(Math.random()*(max-min)+1)+min;
-
- }
-
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。