本文实例为大家分享了java实现简单的猜数字的具体代码,供大家参考,具体内容如下

题目描述:

猜数字(又称 bulls and cows )是一种古老的的密码破译类益智类小游戏,起源于20世纪中期,一般由两个人或多人玩,也可以由一个人和电脑玩。通常由两个人玩,一方出数字,一方猜。出数字的人要想好一个没有重复数字的4个数,不能让猜的人知道。猜的人就可以开始猜。每猜一个数字,出数者就要根据这个数字给出namb,其中a前面的数字n表示数字正确且位置也正确的数的个数,而b前的数字m表示数字正确但位置不正确的数的个数。如正确答案为 5234,而猜的人猜 5346,则是 1a2b,其中有一个5的位置对了,记为1a,而3和4这两个数字对了,而位置没对,因此记为 2b,合起来就是 1a2b。接着猜的人再根据出题者的几a几b继续猜,直到猜中(即 4a0b)为止。

程序要求:

1、满足题意 2、输入数字的合法性3、输出总猜测次数

代码

package practice;
// 猜数字 (bulls and cows)
import java.util.scanner;

public class day0322 {
 public static void main(string[] args) {
  scanner scanner = new scanner(system.in);
  // 产生0000~9999的随机数
  double r = math.random();
  int res = (int)(r * 8999 + 1000);

  int flag = 0;
  // 合法性检查,判断存在重复数字
  while(flag == 0)
  {
   int[] check = new int[10];
   for(int i = 0; i < 10; i ++ ) check[i] = 0;

   check[res / 1000] += 1;check[(res / 100) % 10] += 1;
   check[(res / 10) % 10] += 1;check[res % 10] += 1;

   for(int i = 0; i < 10; i ++ )
    if(check[i] >= 2) {
     r = math.random();
     res = (int)(r * 8999 + 1000);
     flag = 0;
     break;
    }
    else flag = 1;
  }

  // 0000~9999
  system.out.println("答案: " + res);

  int input = -1;
  int idx = 0;
  int times = 0;
  while(input != res)
  {
   system.out.print("请输入你猜的数字: ");
   input = scanner.nextint();
   int inputcopy = input;

   if(input < 0)
   {
    system.out.println("您输入的数字不是四位数!");
    times ++;
    continue;
   }
   int t = 0;
   // 输入数字为4位数,合法性检查
   while(inputcopy != 0)
   {
    inputcopy /= 10;
    t ++;
   }
   if(t != 4)
   {
    system.out.println("您输入的数字不是四位数!");
    times ++;
    continue;
   }

   int n = 0, m = 0;// namb

   if(input == res) break;
   // 输入的各个位数
   int[] a = new int[4];
   a[0] = input / 1000;a[1] = (input / 100) % 10;
   a[2] = (input / 10) % 10; a[3] = (input) % 10;
   // 答案的各个位数
   int[] ans = new int[4];
   ans[0] = res / 1000;ans[1] = (res / 100) % 10;
   ans[2] = (res / 10) % 10; ans[3] = (res) % 10;

   for(int i = 0; i < 4; i ++)
   {
    if(ans[i] == a[i]) n += 1; // a的数量
    for(int j = 0; j < 4; j ++){// b的数量
     if(ans[j] == a[i] && j != i) m += 1;
    }
   }
   system.out.print((++ idx) + ": " + n + "a" + m + "b");
   system.out.println();
   times ++;

  }
  if(input == res){
   times ++;
   system.out.println("4a0b");
   system.out.println("你很厉害啊!");
   system.out.println("猜测次数: " + times);
  }

 }

}

运行效果

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持www.887551.com。