java实现猜数游戏

java实现猜数游戏

一:java实现随机给出一个1-100的随机数
		int num = (int) (Math.random() * 100) + 1;

在这里插入图片描述
在java的Math类中有一个方法可以产生0.0—1.0的double类型小数,通过这段代码可以产生一个1-100的随机数
在这里插入图片描述

二:java完整代码
import java.util.Scanner;
//Math为基础类不需要导包!
//猜数游戏(1-100)
public class Guess {
	public static void main(String[] args) {
		@SuppressWarnings("resource")
		Scanner scan = new Scanner(System.in);
		while (true) {

			int num = (int) (Math.random() * 100) + 1;

			int count = 0;// 计数器,计算猜的次数
			while (true) {
				System.out.println("请输入你猜的数(1-100)");

				int youGuess = scan.nextInt();
				count++;
				if (youGuess > num) {
					System.out.println("你猜大了");
				} else if (youGuess < num) {
					System.out.println("你猜小了");
				} else {
					System.out.println("你猜对了!一共猜了" + count + "次" + "你猜的数为" + youGuess + "随机数为" + num);
					System.out.println("GAME OVER!!");
					break;
				}
			}
			System.out.println("输入y继续游戏,输入其它退出游戏");
			String agin = scan.next();
			if (agin.equals("y")) { // 假如输入y,则继续循环,输入其它通过break语句退出循环
			} else {
				break;
			}
		}

	}
}

  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值