[java]猜数字游戏

蔚落 2021-09-20 22:32 540阅读 0赞

[java]猜数字游戏

【问题描述】:
(1)由计算机随机产生一个数字;
(2)再提示用户输入数字,看计算机随机产生的数字与用户输入的是否一致;
(3)若一致,猜数字成功;
(4)若输入错误,提醒用户 数字猜大了还是猜小了,请用户重新输入新的数字;
注:可以给用户一个难度选择,比如说:将难度分为 (简单 中等 难),对应用户可以猜的次数为10次 5次 2次

【编程思路】:
(1) 编写菜单:提醒用户玩游戏,并选择游戏难度;
(2) 生成随机数;
(3) 循环x次机会
(4) 读取用户的输入并给出相应的提示信息
(5) 根据用户猜测的结果,给出游戏最终结果

【java代码】

  1. import java.util.Random;
  2. import java.util.Scanner;
  3. public class GuessGame {
  4. public static int selectDifficult() {
  5. System.out.println("1. 简单");
  6. System.out.println("2. 中等");
  7. System.out.println("3. 难");
  8. Scanner scanner = new Scanner(System.in);
  9. int difficult = scanner.nextInt();
  10. scanner.nextLine();//一定要加上这行
  11. return difficult;
  12. }
  13. public static int generateRandom(int difficult) {
  14. Random random = new Random();
  15. switch (difficult) {
  16. case 1: return random.nextInt(50);
  17. case 2: return random.nextInt(100);
  18. case 3: return random.nextInt(150);
  19. }
  20. return -1;
  21. }
  22. public static int generateTimes(int difficult) {
  23. Random random = new Random();
  24. switch (difficult) {
  25. case 1: return 10;
  26. case 2: return 5;
  27. case 3: return 2;
  28. }
  29. return -1;
  30. }
  31. public static boolean guess(int r) {
  32. System.out.println("请输入数字:");
  33. Scanner scanner = new Scanner(System.in);
  34. int n = scanner.nextInt();
  35. scanner.nextLine();
  36. if (n == r) {
  37. return true;
  38. } else if (n < r) {
  39. System.out.println("猜小了");
  40. } else {
  41. System.out.println("猜大了");
  42. }
  43. return false;
  44. }
  45. public static void main(String[] args) {
  46. // 1. 难度选择
  47. int difficult = selectDifficult();
  48. // 2. 生成随机数
  49. int r = generateRandom(difficult);
  50. //System.out.println("DEBUG: 随机数是: " + r);// 此行是用来看生成的随机数是多少,调试时用
  51. int times = generateTimes(difficult);
  52. System.out.println("DEBUG: 猜的次数是: " + times);
  53. // 3. 循环 x 次机会
  54. boolean success = false;
  55. for (int i = 0; i < times; i++) {
  56. // 4. 读取用户的输入并且给出合适的提示
  57. success = guess(r);
  58. //System.out.println("DEBUG: 上次猜的结果是: " + success);
  59. if (success) {
  60. break;
  61. }
  62. }
  63. // 5. 根据用户的猜测的结果,给出游戏最终结果
  64. if (success) {
  65. System.out.println("恭喜你,猜对啦,你真聪明");
  66. } else {
  67. System.out.println("很遗憾,没猜对,继续加油喔");
  68. }
  69. }

【运行结果】

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2h5XzEzNjI5Mjc5Mzk4_size_16_color_FFFFFF_t_70

发表评论

表情:
评论列表 (有 0 条评论,540人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Java数字游戏

    思路:应用Math类的random方法随机生成一个0~99之间的数字,将输入的数与系统生成的数在循环当中不断的进行比较,直到猜测的数字正确。 package proj

    相关 数字游戏

    猜数字游戏是令游戏机随机产生一个100以内的正整数,用户输入一个数对其进行猜测,需要你编写程序自动对其与随机产生的被猜数进行比较,并提示大了(“Too big”),还是小了(“

    相关 JAVA数字游戏

    1、随机生成一个0~99(包括0和99)的数字,从控制台输入猜测的数字,输出提示太大还是太小,继续猜测,直到猜到为止,游戏过程中,记录猜对所需的次数,游戏结束后公布结果。

    相关 [java]数字游戏

    \[java\]猜数字游戏 【问题描述】: (1)由计算机随机产生一个数字; (2)再提示用户输入数字,看计算机随机产生的数字与用户输入的是否一致; (