package com.lovecoding.J20250511; import java.util.Random; import java.util.Scanner; /** * @author WanJl * @version 1.0 * @title Demo01 * @description 猜数字游戏:使用Random生成一个1~100(包括1和100)的随机整数。通过键盘录入猜数字是哪一个? * 如果猜到的比生成的大,就输出:猜大了,请继续输入... * 如果猜到的比生成的小,就输出:猜小了,请继续输入.... * 如果猜到的和生产的相等,就输出:猜对了。结束程序.... * 考点: * 数据类型,输出语句,if...else分支结构,for循环结构。Random随机数对象。Scanner键盘输入对象。运算符(算术运算符、赋值运算符、比较运算符) * @create 2025/5/11 */ public class Demo01 { public static void main(String[] args) { //使用Random对象的nextInt()方法 --推荐这种 /* 0.0~1.0 0.1 0.11111 0.15321564 0.1465164 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 //使用Math.random()方法 for (int i = 0; i < 20; i++) { //生成的double类型值,double类型占用内存是多少位? 64 int 32位 System.out.println(Math.random()*100); } */ Random ran = new Random(); int n = ran.nextInt(100) + 1; //生成的随机数的范围是:0~100之间,包括0,但是不包括100 //键盘输入 Scanner sc = new Scanner(System.in); while (true) { System.out.println("请输入一个整数:"); int input = sc.nextInt(); if (input > n) System.out.println("猜大了,请重新输入"); else if (input < n) System.out.println("猜小了,请重新输入"); else break; } System.out.println("猜对了,恭喜"); } }