1、生成6位不重复的两位随机数
/生成6位不重复的两位随机数
//生成6个两位数
//不重复
//用数组去做
Random rand = new Random();
//声明数组变量,存储随机数
final int N = 6;
int[] array = new int[N];
array[0] = 10+rand.nextInt(90);
//实现循环
for (int i = 1,t; i < N; i++) {
t = 10+rand.nextInt(90);
if(array[i] != t){
array[i] = t;
}else{
i--;
continue;
}
}
for (int i = 0; i <N ; i++) {
System.out.println(array[i]);
}
运行结果
2
2、求1~1000之间的质数
/求1~1000之间的质数
//找质数,只要找到范围最大开平方之前的一个就可以了:即求2~Math.sqrt(NUm)之间的质数就可以了,开方往后就没有质数了
//质数是除了1和他本身,不能被其他数整除
//用数组的方式存储值
final int N = 1000;
int[] array = new int[N];
int index = 0;
//已经知道2是质数,所以先将2赋值给第一个数组
array[index++] = 2;
//定义布尔值用于假设判断,是否是质数
boolean isPM;
//外循环控制循环的数字,从1~N
//内循环进行判断是否是质数,然后赋值
for (int i = 3; i <N ; i++) {
//先假设成立,如果不是质数,就赋值false
isPM = true;
//只需要判断从2~Math.sqrt(i)之间是不是质数就可以了
//为什么要加=?,包括开平方,不是包括她本事,,如果不包括开平方,4.9等等也能算进去质数
for (int j = 2; j<=Math.sqrt(i) ; j++) {
if(i%j == 0){
//如果是质数,赋值false,然后终止循环
isPM=false;
break;
}
}
if(isPM){
//下面是省略写法,先将质数的值赋值给数组,在将下标index加1
array[index++] = i;
}
}
//输出数组,注意输出方式
for (int i = 0; i <index; i++) {
System.out.print(array[i]+"\t");
//可以规定输出格式,每十个数换一行
if((i+1)%9 == 0){
System.out.println();
}
}
运行结果
3 生成10个0~100之间的整数成绩,求最大成绩,最小成绩,前三名成绩,求平均成绩
final int CAPACITY = 10;
int[] scores = new int[CAPACITY];
double avgScore = 0;
int i = 0;
scores[i++] = rand.nextInt(101);
for(int j,temp;i<CAPACITY;i++){
temp = rand.nextInt(101);
avgScore += temp;
//在外面i加过一次,所以下面的下标是i-1;
if(temp >= scores[i-1]){
scores[i] = temp;
continue;
}
//将条件写进去for判断
//插入排序
//将值往后移
for( j = i-1;j>=0 && scores[j]>temp ;j--){
//初始化为i-1,所以前面写j+1
scores[j+1] = scores[j];
}
//循环出来,j+1的下标就是要插入的位置
//要想j作用域大,在最外层循环就定义
scores[j+1] = temp;
}
System.out.println((avgScore-scores[0]-scores[CAPACITY-1])/(CAPACITY-2));
for (int j = 1; j <= 3; j++) {
System.out.println(scores[CAPACITY-j]);
}