简单的一个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);
}
}