java实现猜数游戏

经典猜数游戏案例

方法一
public static void main(String[] args) {
        //1.随机生成一个1-100的随机整数
        Random rand = new Random();
        int a = 1;
        int b = 100;
        int n = rand.nextInt(a, b + 1);

        int i = 0;
        //2.条件循环语句
        while (true) {
            if(i>=10){
                System.err.printf("%d、游戏结束,智商太低,游戏:(%d)分。%n", i, 0);
                break;
            }
            System.out.printf("请输入数字[%d-%d]:%n", a, b);

            //3.键盘输入数字
            int t = new Scanner(System.in).nextInt();
            ++i;

            if (t == n) {
                System.out.printf("%d、恭喜您,猜对了,你的游戏:(%d)分。%n", i, (100 - i * 10 + 10));

                //退出循环语句
                break;
            } else if (t > n) {
                System.out.printf("%d、太大了。%n", i);
            } else {
                System.out.printf("%d、太小了。%n", i);
            }
        }
    }

方法二
public static void main(String[] args) {
                        //随机类
                  Random rand = new Random();
                  //键盘输入
                  Scanner sc = new Scanner(System.in);
                  //出题
                  int num = rand.nextInt(100) + 1;
                  int n = 0;
                  while (true) {
                      ++n;
                      int temp = 0;
                      System.out.print("请输入数字[1-100]:");
                      if (sc.hasNextInt()) {
                          temp = sc.nextInt();
                      } else {
                          String s = sc.next();
                          if ("quit".contains(s)) {          
                              sc.close();
                              System.out.printf("程序退出,游戏结束!%n");
                              break;
                          }
                          System.out.printf("输入有误%s,请重新输入!%n", s);
                          continue;
                      }
                      if (temp > num) {
                          System.out.printf("%d、太大了%n", n);
                      } else if (temp < num) {
                          System.out.printf("%d、太小了%n", n);
                      } else {
                          if (n == 1) {
                              System.out.printf("大神:你猜对了,你的游戏成绩:%d分", 100);
                          } else {
                              System.out.printf("%d、恭喜:你猜对了,你的游戏成绩:%d分", n, 110 - n * 10);
                          }
                          break;
                      }
                  }
              }
     }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值