完成一个猜数字游戏,通过随机数方法编写一个小游戏程序

2024-12-02 07:48:05
推荐回答(2个)
回答1:

  我自己编写的一个小程序,没有用到什么高深的技术,都是些基础的,希望对你有帮助
  public class GuessNum {

  public static void main(String[] args) {
  GuessNum.play();
  }

  static Scanner sc = new Scanner(System.in);

  static int guessCount = 0;

  // 生成不重复的随机数
  public static String[] generationNum(int count){
  String [] sNum = new String[count];

  int n = 10;

  Random ran = new Random();

  boolean[] bool = new boolean[n];

  int num = 0;

  for(int i=0;i
  do{
  num = ran.nextInt(n);
  }while(bool[num]);

  bool[num] = true;

  sNum[i] = String.valueOf(num);
  }

  return sNum;
  }

  // 获取猜测结果
  public static String getResult(String[] num, String inputNum){

  String resultMessage = "";
  int rightInAll = 0;
  int rightInNum = 0;
  int numLength = inputNum.length();

  // 根据输入的数与生成的数作比较(这里判断输入数有生成的数,且位置相同)
  for(int i=0;i
  // 判断输入数与生成数各位数是否相同
  if(num[(num.length-1) - i].equals(inputNum.substring(numLength - 1, numLength))){
  rightInAll++;
  }
  numLength--;
  }

  // 这里判断输入数有生成的数,但位置不同
  for(int j=0;j  if(inputNum.indexOf(num[j]) > -1){
  rightInNum++;
  }
  }

  resultMessage = rightInAll + "A" + (rightInNum - rightInAll) + "B";

  return resultMessage;
  }

  public static void startGame(int count){
  boolean continueOrNot = false;
  String resultNum = "";
  String [] num = GuessNum.generationNum(count);

  for(int i=0;i  resultNum += num[i];
  }

  do{
  System.out.print("input:");
  boolean maxLengthError = false;
  String inputNum = sc.next();

  if(inputNum.length() > count){
  System.out.println("The max length is " + count);
  maxLengthError = true;
  }

  if(inputNum.length() != count){
  System.out.println("Enter the " + count + " digit.");
  maxLengthError = true;
  }

  try{
  Integer.valueOf(inputNum);
  String message = GuessNum.getResult(num, inputNum);
  System.out.println("Guess:" + inputNum + "\tResult:" + message);
  guessCount++;

  if(guessCount > 10){
  break;
  }

  continueOrNot = winOrNot(message,resultNum,count);
  }catch(Exception e){
  String message = "";
  if(maxLengthError){
  message += "and ";
  }
  System.out.println(message + "It is not Number.");
  System.out.println("Input again.");
  }

  }while(continueOrNot == false);

  }

  public static boolean winOrNot(String message,String resultNum,int count){

  if((count + "A0B").equals(message)){
  System.out.println("ResultNum:" + resultNum + "\tguessCount:" + guessCount);
  System.out.println("You Win.");
  return true;
  }
  return false;
  }

  public static void play(){
  boolean again = false;
  int count = 4;
  do{
  GuessNum.startGame(count);
  System.out.println("continue?Enter y to continue.");
  if("y".equals(sc.next().toLowerCase())){
  again = true;
  }
  }while(again);

  System.out.println("Game Over.");
  }

  }

回答2:

0098675231