Java项目与练习 01 猜数字

       简单的一个Java小游戏,利用while无限循环直至用户猜出数字。

       可支持设置用户名,记录游戏时间及猜测次数

示例

       有更新再次更改

import java.util.Random;
import java.util.Scanner;

/**
 * 项目简介:
 * 简单的猜数字入门小游戏,额外记录游戏时间及游戏次数
 *
 * @author 心斐
 * @time 2022/9/8-11:49
 * 可考虑功能:
 * 账户密码,再来一局,排行榜(时间、次数)
 */
public class guessNum {
    static long start;

    public static void main(String[] args) {
        System.out.println("Welcome XinFei's game,please tell me what's your name?");//欢迎语
        //利用Scanner获取用户名
        Scanner ss = new Scanner(System.in);
        String name = ss.nextLine();
        System.out.println("Well,understand.You're" + name + ".Welcome!");
        System.out.println("Let's play a game--'GUESS NUMBER'");
        // 生成[1,100]区间的整数
        Random r = new Random();
        int key = r.nextInt(100) + 1;//0~99+1=1~100
        //利用Scanner获取用户所想的值
        Scanner sn = new Scanner(System.in);
        System.out.println("I get it.Enter the number you think right through 0~100.");
        int count = 0;//初始化猜测次数
        //利用while无限循环直至用户猜准为止
        int i = 1;
        while (true) {
            //正式输入猜测值后开始计时
            int num = sn.nextInt();
            while (i == 1) {
                start = System.currentTimeMillis();//开始计时
                i++;
            }
            count += 1;//当用户每一次进行猜测后累计增加
            if (num > key) {//判断用户猜测数大于随机数时进行提示
                System.out.println("It's bigger than me!");
            } else if (num < key) {//判断用户猜测数小于随机数时进行提示
                System.out.println("HAHA!It's so small!");
            } else {//当用户猜测数等于随机数时进行提示
                System.out.println("Congratulation!You're right!So smart!");
                break;//猜测正确,退出循环
            }
        }
        long end = System.currentTimeMillis();//结束计时
        long runTime = end - start;
        System.out.println("Your time:" + runTime / 1000 + "s");
        System.out.println("Your count:" + count);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值