zoukankan      html  css  js  c++  java
  • 【JAVA】猜数字

    import java.util.*;
    
    public class GN {
        public static void main(String arg[]) {
            int a = 0;// 数字标记
            int b = 0;// 位置标记
            int time = 0;// 次数
            int rdn[] = new int[5];
            Random rd = new Random();
    
            do {
                rdn[0] = rd.nextInt(9);
                rdn[1] = rd.nextInt(9);
                rdn[2] = rd.nextInt(9);
                rdn[3] = rd.nextInt(9);// 生成四个随机数字。
                if (rdn[0] == 0 || rdn[0] == rdn[1] || rdn[0] == rdn[2]
                        || rdn[0] == rdn[3] || rdn[1] == rdn[2] || rdn[1] == rdn[3]
                        || rdn[1] == rdn[4] || rdn[2] == rdn[3] || rdn[2] == rdn[4]
                        || rdn[3] == rdn[4])
                    continue;
                else
                    break;
            } while (true);
    
            do {
                System.out.println("请输入您所猜的数字:");
                Scanner s = new Scanner(System.in);
                int n = s.nextInt();
                String x = String.valueOf(n);
                if (n == 1)
                    System.out.println(rdn[0] + "" + rdn[1] + "" + rdn[2] + ""
                            + rdn[3]);
                int num[] = new int[4];
                num[0] = n / 1000;
                num[1] = n / 100 % 10;
                num[2] = n % 100 / 10;
                num[3] = n % 10;// 处理键入的数字
                if (num[0] == 0) {
                    System.out.println("输入的数字不能以零开头,请重新输入。");
                } else if (x.length() > 4 || x.length() <= 0)
                    System.out.println("输入的数字不符合要求,请重新输入。");
                else if (x.length() == 4) {
                    time++;
                    a = 0;
                    b = 0;
                    for (int i = 0; i <= 3; i++) {
                        for (int j = 0; j <= 3; j++) {
                            if (num[i] == rdn[j])
                                if (i == j)
                                    b++;
                                else
                                    a++;
    
                        }
                    }
                    if (b != 4)
                        System.out.println("数字相同而位置不同有 " + a + " 个,位置和数字都相同有 " + b
                                + "");
                    if (b != 4 && time > 5)
                        System.out.println("你个笨蛋,都猜" + time + "次了,还猜不对!");
                }
                if (b == 4) {
                    System.out.println("恭喜你,猜对了!一共猜了" + time + "次。");
                    break;
                }
            } while (true);
    
        }
    
    }
  • 相关阅读:
    【数学建模】—优秀论文(一)
    【数学建模】—论文排版
    【Linux学习】—第8章linux编程
    【Linux学习】—文件权限和目录配置
    【ESP8266学习】(一)
    【OpenCV】——b站达尔闻
    【Linux学习】——Shell编程基础
    【数学建模】——模拟退火算法(SAA)
    react 开发中火狐,Safari浏览器嵌套iframe显示空白
    element ui dataPicker 日期范围限制
  • 原文地址:https://www.cnblogs.com/niray/p/3750022.html
Copyright © 2011-2022 走看看