Files
javaSE251223/day07/src/com/inmind/random02/Demo07.java
2025-12-29 12:00:14 +08:00

54 lines
2.2 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package com.inmind.random02;
import java.util.Random;
import java.util.Scanner;
/*
常用类_Random_猜数字游戏(1~100)
猜数字小游戏
游戏开始时会随机生成一个1-100之间的整数number 。
玩家猜测一个数字guessNumber 会与number 作比较,系统提示大了或者小了,直到玩家猜中,游戏结束。
分析:
1.使用random类获取一个随机值(1~100)
2.使用scanner输入你所猜的值,假设输入的是33
死循环while(true)
a.将输入的猜的值跟随机数做比较如果猜的值大了需要提示猜的值33大了
b.将输入的猜的值跟随机数做比较如果猜的值小了需要提示猜的值33小了
c.将输入的猜的值跟随机数做比较,如果猜的值一致,需要提示正确,并结束游戏
*/
public class Demo07 {
public static void main(String[] args) {
//1.使用random类获取一个随机值(1~100)
Random random = new Random();
//1~100 -1 0~99
int number = random.nextInt(1, 101);
//2.使用scanner输入你所猜的值,假设输入的是33
Scanner sc = new Scanner(System.in);
//死循环while(true)
while (true) {
//获取用户猜测的值
System.out.println("请输入您所猜的值:");
int guessNumber = sc.nextInt();
if (guessNumber > number) {
//a.将输入的猜的值跟随机数做比较如果猜的值大了需要提示猜的值33大了
System.out.println("您猜的值"+guessNumber+",大了");
} else if (guessNumber < number) {
//b.将输入的猜的值跟随机数做比较如果猜的值小了需要提示猜的值33小了
System.out.println("您猜的值"+guessNumber+",小了");
}else{
//c.将输入的猜的值跟随机数做比较,如果猜的值一致,需要提示正确,并结束游戏
System.out.println("恭喜您,猜对了");
//猜对了,结束死循环
break;
}
}
System.out.println("程序结束了!!!");
}
}