这里是让计算机去猜自己产生的随机数~~~
import java.util.Random;
class UsingRandom {
public static void main(String[] args) {
Random rd=new Random();
int result = rd.nextInt(101);//Random产生的随机数
System.out.println("Random猜Random - - 呵呵");
int count = 0;//猜的次数
int currentMaxRange=101;//猜完后,所在的最大范围
int currentMinRange=0;//猜完后,锁在的最小范围
int currentRD=rd.nextInt(101);//当前计算机猜的数
while(true){
if(currentRD > result){
System.out.println(currentRD);
count++;
currentMaxRange = currentRD;
currentRD = rd.nextInt(currentMaxRange-currentMinRange)+currentMinRange;
continue;
}else if(currentRD < result){
System.out.println(currentRD);
count++;
currentMinRange = currentRD+1;
currentRD = rd.nextInt(currentMaxRange-currentMinRange)+currentMinRange;
continue;
}else{
count++;
System.out.println(currentRD);
System.out.println("恭喜计算机,猜对了。共猜了"+count+"次");
break;
}
}
}
}
|
|