使用java怎么编写一个猜数字游戏

发布时间:2020-12-30 14:30:30 作者:Leah
来源:亿速云 阅读:126

使用java怎么编写一个猜数字游戏?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。

代码如下:

public static void main(String[] args) {
 Random rand = new Random();
 Scanner sc = new Scanner(System.in);
 System.out.println("----------猜数游戏----------");
 System.out.println("  1.开始游戏\n  2.游戏设置\n  3.退出游戏");
 System.out.println("请输入:");
 int[] arr = new int[3];
 for (int i = 1; i < arr.length; i++) {
  if (i < 4) {
  arr[i] = sc.nextInt();
  }
  break;
 }
 int a = 0;
 //开始界面
 for (int i = 1; i < arr.length; i++) {
  if (arr[i] == 1) {
  System.out.println("开始游戏");
  a = 1;
  break;
  } else if (arr[i] == 2) {
  System.out.println("游戏设置");
  a = 2;
  break;
  } else if (arr[i] == 3) {
  System.out.println("退出游戏");
  a = 3;
  break;
  } else System.out.println("错误输入");
 }
 //设置界面
 int max = 100;
 int min = 0;
 int cishu = 5;
 if (a == 2) {
  System.out.println("设置范围");
  System.out.println("最小值");
  min = sc.nextInt();
  System.out.println("最大值");
  max = sc.nextInt();
  System.out.println("设置猜的次数");
  cishu = sc.nextInt();
  //int randNum = rand.nextInt(max - min + 1) + min;
  System.out.println("设置范围\n最小值为:" + min + "\n最大值为:" + max + "\n猜的次数为:" + cishu);
  a = 6;
 }
 //设置后回到开始界面
 if (a==6){
  System.out.println("----------猜数游戏----------");
  System.out.println("  1.开始游戏\n  2.游戏设置\n  3.退出游戏");
  System.out.println("请输入:");
  for (int i = 1; i < arr.length; i++) {
  if (i < 4) {
   arr[i] = sc.nextInt();
  }
  break;
  }
  //开始界面
  for (int i = 1; i < arr.length; i++) {
  if (arr[i] == 1) {
   System.out.println("开始游戏");
   a = 1;
   break;
  } else if (arr[i] == 2) {
   System.out.println("游戏设置");
   a = 2;
   break;
  } else if (arr[i] == 3) {
   System.out.println("退出游戏");
   a = 3;
   break;
  } else System.out.println("错误输入");
  }
 }
 //游戏界面
 if (a == 1) {
  int randNum = rand.nextInt(max - min + 1) + min;
  System.out.println("我想了一个" + min + "到" + max + "的数,请你来猜:\n你有" + cishu + "次机会");
  int i = 1;
  for (; i <= cishu; ++i) {
  System.out.println("第" + i + "次:");
  int guess = sc.nextInt();
  if (i < cishu) {
   if (randNum >= guess) {
   if (randNum <= guess) {
    System.out.println("恭喜你猜对了!\n" + "该值是:" + randNum);
    break;
   } else System.out.println("你猜小了!");
   } else System.out.println("你猜大了!");
  } else System.out.println("你猜错了!\n该值是:" + randNum);
  }
 }
}

运行结果:

使用java怎么编写一个猜数字游戏

看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注亿速云行业资讯频道,感谢您对亿速云的支持。

推荐阅读:
  1. C++编写的一个简单的猜数字游戏源码
  2. 使用java编写一个rmi的方法

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

java ava

上一篇:怎么在PostgreSQL数据库中对重复数据进行处理

下一篇:使用springboot怎么对数据库的密码进行加密

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》