[java]猜数字游戏
[java]猜数字游戏
【问题描述】:
(1)由计算机随机产生一个数字;
(2)再提示用户输入数字,看计算机随机产生的数字与用户输入的是否一致;
(3)若一致,猜数字成功;
(4)若输入错误,提醒用户 数字猜大了还是猜小了,请用户重新输入新的数字;
注:可以给用户一个难度选择,比如说:将难度分为 (简单 中等 难),对应用户可以猜的次数为10次 5次 2次
【编程思路】:
(1) 编写菜单:提醒用户玩游戏,并选择游戏难度;
(2) 生成随机数;
(3) 循环x次机会
(4) 读取用户的输入并给出相应的提示信息
(5) 根据用户猜测的结果,给出游戏最终结果
【java代码】
import java.util.Random;
import java.util.Scanner;
public class GuessGame {
public static int selectDifficult() {
System.out.println("1. 简单");
System.out.println("2. 中等");
System.out.println("3. 难");
Scanner scanner = new Scanner(System.in);
int difficult = scanner.nextInt();
scanner.nextLine();//一定要加上这行
return difficult;
}
public static int generateRandom(int difficult) {
Random random = new Random();
switch (difficult) {
case 1: return random.nextInt(50);
case 2: return random.nextInt(100);
case 3: return random.nextInt(150);
}
return -1;
}
public static int generateTimes(int difficult) {
Random random = new Random();
switch (difficult) {
case 1: return 10;
case 2: return 5;
case 3: return 2;
}
return -1;
}
public static boolean guess(int r) {
System.out.println("请输入数字:");
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
scanner.nextLine();
if (n == r) {
return true;
} else if (n < r) {
System.out.println("猜小了");
} else {
System.out.println("猜大了");
}
return false;
}
public static void main(String[] args) {
// 1. 难度选择
int difficult = selectDifficult();
// 2. 生成随机数
int r = generateRandom(difficult);
//System.out.println("DEBUG: 随机数是: " + r);// 此行是用来看生成的随机数是多少,调试时用
int times = generateTimes(difficult);
System.out.println("DEBUG: 猜的次数是: " + times);
// 3. 循环 x 次机会
boolean success = false;
for (int i = 0; i < times; i++) {
// 4. 读取用户的输入并且给出合适的提示
success = guess(r);
//System.out.println("DEBUG: 上次猜的结果是: " + success);
if (success) {
break;
}
}
// 5. 根据用户的猜测的结果,给出游戏最终结果
if (success) {
System.out.println("恭喜你,猜对啦,你真聪明");
} else {
System.out.println("很遗憾,没猜对,继续加油喔");
}
}
【运行结果】
还没有评论,来说两句吧...