Random 类
- [11.7 Random 类](#11.7 Random 类)
11.7 Random 类

【例11.32】生成10个随机数字,且数字不大于100
java
package jiaqi;
import java.util.Random;
public class demo342_2 {
public static void main(String[] args) {
// TODO 自动生成的方法存根
Random rd = new Random();
for(int i=0;i<10;i++)
{
// int t = rd.nextInt(100);
System.out.print( rd.nextInt(100) + " ");
}
}
}
【实例】:实现36选7程序
编写36选7的彩票程序。
既然Random可以产生随机数,那么利用它来实现36选7的功能。最大值到36,所以设置边界的数值就是37,并且里面不能有0或者是重复的数据.
java
package jiaqi;
import java.util.Random;
public class demo342_2
{
public static void main(String[] args)
{
// TODO 自动生成的方法存根
Random rd = new Random();
// System.out.println();
int idx = 0 ;
int ans[] = new int[7];
while (true)
{
int t = rd.nextInt(37);
if(is_true(t,ans))
{
ans[idx++] = t;
}
if(idx==7)break;
}
for(int i=0;i<7;i++)
{
System.out.println(ans[i]);
}
}
public static boolean is_true(int t,int ans[])
{
if(t==0)
{
return false;
}
for(int i =0 ;i < 7;i++)
{
if(t==ans[i])return false;
}
return true;
}
}