题目:给定整数范围值,并用随机数产生范围内的值,用户输入值进行判断大小以及是否正确。

public static void main(String[] args) {
Random random=new Random();//定义随机数
int[] nums = {100, 500, 1000, 2000, 5000};//定义数组
int n = nums[random.nextInt(nums.length)] ;
int m=1;
int y=random.nextInt(m,n+1);//生成m到n的随机数,n为数组nums中的数
int index=0;
long start=System.currentTimeMillis();//获得开始游戏时间戳
while (true){
Scanner sc=new Scanner(System.in);
System.out.printf("\033[36m请输入数字[%d,%d]:\033[0m",m,n);
int x=sc.nextInt();
++index;
if (x>y){
System.out.printf("\033[31m第%d次、太大了\033[0m%n",index);
} else if (x<y){
System.out.printf("\033[31m第%d次、太小了\033[0m%n",index);
}else {
long end=System.currentTimeMillis();//获得答对游戏时间戳
System.out.printf("\033[32m第%d次、恭喜你猜对了,你的分数为%d,用时%d秒\033[0m%n",index,(110-10*index),(end-start)/1000);//算出输入正确数字,游戏共计多长时间。
break;
}
}
}

Java-猜数字游戏(升级版)_游戏