Java-guess the number game (upgraded version)

Topic: Given an integer range value, and use a random number to generate a value within the range, the user enters the value to determine the size and whether it is correct.

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;
        }
    }
}

insert image description here

Guess you like

Origin blog.csdn.net/qq_59088934/article/details/128448919