JAVA实现人机猜拳

目录

基础版

运行截图

升级版


我们的实训内容是java,害,说实话java不怎么智能的感觉,以下是老师布置的小作业吧,直接复制就能运行(懒得写注释,都是基础代码)

服了,用了老师没有教的知识就被说是抄的,真dog

基础版

话不多说,上代码

import java.util.*;

public class Main {
    static String biao = "\n********************\n";
    static boolean LoginBoolean = false;
    static String[] data = new String[2];

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        Main.menu(input);
    }

    public static void Register(Scanner input) {
        String user, password;
        password = "";

        System.out.print("" + biao + "<<请填写个人信息>>\n");
        user = input.nextLine();
        do {
            if (!Objects.equals(user, "")) {
                System.out.print("请输入您的密码:");
                password = input.nextLine();
            } else {
                System.out.print("请输入您的名字:");
                user = input.nextLine();
            }
        } while (Objects.equals(user, "") || Objects.equals(password, ""));


        data[0] = user;
        data[1] = password;
        LoginBoolean = true;
        System.out.println("\n注册成功!\n");

    }

    public static int getmenuid(Scanner input) {
        int id = 0;
        try {
            id = Integer.parseInt(input.next());
            //天坑,未知的死循环呀
            //id=input.nextInt();
            if (id > 0 && id < 4) {
                return id;
            } else {
                System.out.println("请输入合法数据\n");
            }
        } catch (Exception e) {
            System.out.print("请输入合法数据\n");
        }
        return 0;
    }

    public static void menu(Scanner input) {
        int id = 0;
        String tishi = "菜单\n 1 注册\n 2 登陆\n 3 开奖\n 请输入编号:";

        while (true) {
            boolean break_ = true;
            System.out.print(tishi);
            id = getmenuid(input);
            switch (id) {
                case 1:
                    Main.Register(input);
                    break;
                case 2:
                    if (LoginBoolean)
                        Login(data[0]);
                    else {
                        System.out.println("检测到你还没有注册,请注册\n");
                    }
                    break;
                case 3:
                    if (LoginBoolean) {
                        int UserRes = 0;
                        UserRes = Objects.requireNonNull(Main.CreatRandom(1))[0];
                        int[] AllRes = Main.CreatRandom(5);
                        //断言防止为空
                        assert AllRes != null;

                        break_ = pandaun(UserRes, AllRes);
                    } else {
                        System.out.println("检测到你还没有注册,请注册\n");
                        Main.Register(input);
                    }
                    break;
            }
            if (id != 0) {
                if (!break_)
                    break;
                System.out.println("是否(y/n)继续");
                String temp = input.next();
                if (temp != null) {
                    if (temp.equals("n")) {
                        break;
                    }
                }
            }
        }
    }

    public static int[] CreatRandom(int sum) {
        if (LoginBoolean) {
            int[] random_ = new int[sum];
            Random r = new Random();
            //随机数产生,【1000~9000+1)
            for (int i = 0; i < sum; i++) {
                int a = r.nextInt(9000 + 1) + 1000;
                random_[i] = a;
            }
            return random_;

        } else {
            System.out.println("请注册登陆");
            return null;
        }
    }

    public static boolean pandaun(int UserId, int[] RandomId) {
        for (int randomdatum : RandomId) {
            if (UserId == randomdatum) {
                System.out.println("恭喜你是今天的幸运星");
            }
        }
        System.out.println("很遗憾是你不是今天的幸运星\n欢迎您的下次参与\n");
        return false;
    }

    public static void Login(String user) {
        if (LoginBoolean) {
            System.out.println("欢迎你 " + user + "\n");
        } else {
            System.out.println("请注册");
        }
    }
}

运行截图

JAVA实现人机猜拳_第1张图片JAVA实现人机猜拳_第2张图片

升级版

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.*;

import com.alibaba.fastjson2.JSONObject;
import com.mysql.cj.xdevapi.JsonString;
import org.apache.commons.io.*;
import com.alibaba.fastjson2.JSON;
import com.sun.javafx.collections.MappingChange;

public class Main {
    static String biao = "\n********************\n";
    static boolean LoginBoolean = false;
    static String[] data = new String[2];
    //初始化JSON内key-value的个数
    static int length = 0;
    //用户的登录次数
    static int global_login_sum = 0;
    //用户随机的幸运数字
    static int UserRes;

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        Main.menu(input);
    }

    public static void Register(Scanner input, String path) {
        String user, password;
        password = "";

        System.out.print("" + biao + "<<请填写个人信息>>\n");
        user = input.nextLine();
        do {
            if (!Objects.equals(user, "")) {
                System.out.print("请输入您的密码:");
                password = input.nextLine();
            } else {
                System.out.print("请输入您的名字:");
                user = input.nextLine();
            }
        } while (Objects.equals(user, "") || Objects.equals(password, ""));

        if (Json(user, password, path)) {
            data[0] = user;
            data[1] = password;
            LoginBoolean = true;
        }
    }

    public static int getmenuid(Scanner input) {
        int id = 0;
        try {
            id = Integer.parseInt(input.next());
            //天坑,未知的死循环呀
            //id=input.nextInt();
            if (id > 0 && id < 4) {
                return id;
            } else {
                System.out.println("请输入合法数据\n");
            }
        } catch (Exception e) {
            System.out.print("请输入合法数据\n");
        }
        return 0;
    }

    public static void menu(Scanner input) {
        int id = 0;
        String tishi = "菜单\n 1 注册\n 2 登陆\n 3 开奖\n 请输入编号:";
        String path = "data.json";

        UserRes = (Main.CreatRandom(1))[0];

        while (true) {

            boolean break_ = true;
            System.out.print(tishi);
            id = getmenuid(input);

            switch (id) {
                case 1:
                    Main.Register(input, path);

                    break;
                case 2:
                    if (LoginBoolean)
                        Login(data[0], UserRes);
                    else {
                        Main.Register(input, path);

                    }
                    break;
                case 3:
                    if (LoginBoolean) {
                        int[] AllRes = Main.CreatRandom(5);
                        //断言防止为空报错

                        break_ = pandaun(UserRes, AllRes);
                    } else {
                        System.out.println("您还没登录已跳至登录\n");
                        Main.Register(input, path);
                    }
                    break;
            }
            //判断输入错误的次数是否大于3
            if (global_login_sum >= 3) {
                System.out.println("密码错误3次,已退出系统");
                break;
            }


            if (id != 0) {
                if (!break_)
                    break;
                System.out.println("是否(y/n)继续");
                String temp = input.next();
                if (temp != null) {
                    if (!temp.equals("y") && !temp.equals("n")) {
                        do {
                            System.out.println("请输入合法参数\n");
                            temp = input.next();

                        } while (!Objects.equals(temp, "y") && !Objects.equals(temp, "n"));
                        if (temp.equals("n")) {
                            break;
                        }
                    } else {
                        if (temp.equals("n")) {
                            break;
                        }
                    }
                }
            }
        }
    }

    public static int[] CreatRandom(int sum) {
        int[] random_ = new int[sum];
        Random r = new Random();
        //随机数产生,【1000~9000+1)
        for (int i = 0; i < sum; i++) {
            int a = r.nextInt(9000 + 1) + 1000;
            random_[i] = a;
        }
        return random_;

//        } else {
//            System.out.println("请注册登陆");
//            return null;
//        }
    }

    public static boolean pandaun(int UserId, int[] RandomId) {
        for (int randomdatum : RandomId) {
            if (UserId == randomdatum) {
                System.out.println("恭喜你是今天的幸运星");
            }
        }
        System.out.println("很遗憾是你不是今天的幸运星\n欢迎您的下次参与\n");
        return false;
    }

    public static void Login(String user, int UserId) {
        if (LoginBoolean) {
            System.out.println("欢迎你 " + user + "\n您今天的幸运数字是:" + UserId);
        } else {
            System.out.println("请注册");
        }
    }

    //增加新用户
    public static void AddNewUser(String user, String password, int length, String path) {
        File file = new File(path);
        //文件读取
        String file1 = null;
        try {
            //以字符串的形式读取出来
            file1 = FileUtils.readFileToString(file);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        //初始化ex变量用于记录用户在JSON文件中的状态
        int ex = 0;
        //JSON读取
        //JSON字符串转转为json对象
        JSONObject jsonobject = JSON.parseObject(file1);
        //新注册用户数据写入
        //加入新元素信息
        //最内层的构建
        Map map = new HashMap();
        map.put(user, password);
        //弟2层构建
        Map> map2 = new HashMap>();
        map2.put(String.valueOf(length + 1), map);
        //将构建的数据插入
        jsonobject.putAll(map2);
        //将json对象转JSON字符串
        String jsonstring = JSON.toJSONString(jsonobject);
        try {
            //重新写入json内容
            //new FileOutputStream(file),没有加true就是覆盖重写,加了的话是追加
            Writer write = new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8);
            write.write(jsonstring);
            write.flush();
            write.close();
        } catch (Exception e) {
            System.out.println("配置文件写入失败");
        }
    }

    //JSON文件初始化
    public static void InitJson(String path) {

        File file = new File(path);
        // 判断文件是否存在
        if (!file.exists()) {
            // 创建文件
            try {
                if (file.createNewFile()) {
                    System.out.println(path + " 创建成功");
                    //初始化JSON
                    String init_json = "{\"data\":{\"user\":\"password\"}}";
                    try {
                        Writer write = new OutputStreamWriter(new FileOutputStream(file, true), StandardCharsets.UTF_8);
                        write.write(init_json);
                        write.flush();
                        write.close();
                    } catch (Exception ignored) {
                        System.out.println("配置文件初始化失败");
                    }
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    public static int GetJsonStatus(String user, String password, String path) {
        File file = new File(path);
        //文件读取
        String file1 = null;
        try {
            //以字符串的形式读取出来
            file1 = FileUtils.readFileToString(file);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        //初始化ex变量用于记录用户在JSON文件中的状态
        int ex = 0;
        //JSON读取
        //JSON字符串转转为json对象
        JSONObject jsonobject = JSON.parseObject(file1);
        //注意至0
        length = 0;
        //对JSON对象进行遍历
        for (Map.Entry entry : jsonobject.entrySet()) {
            //统计原JSON内key-value的个数
            length++;
            //将用户名,密码的集合存于maptemp中
            Map maptemp = (Map) jsonobject.get(entry.getKey());
            //获取密码
            String json_password = maptemp.get(user);
            //如果密码为空说明用户没有注册
            if (json_password != null) {
                //用户已注册状态
                ex = 3;
                //密码正确
                if (Objects.equals(password, json_password)) {
                    ex = 1;
                }
                //密码错误
                else {
                    ex = 2;
                }
            }
        }
        return ex;
    }

    public static boolean Json(String user, String password, String path) {
        //JSON文件初始化
        InitJson(path);
        //获取当前用户的账号状态
        int ex = GetJsonStatus(user, password, path);
        //对当前用户状态进行筛选
        if (ex == 0) {
            System.out.println("\n检测到您为新用户\n注册成功!\n");
            AddNewUser(user, password, length, path);
            LoginBoolean = true;
            Login(user, UserRes);
        }
        if (ex == 1) {
            System.out.println("密码正确,正在登陆...\n登录成功!");
            return true;
        }
        if (ex == 2) {
            global_login_sum++;
            System.out.println("密码不正确\n你还有" + (3 - global_login_sum) + "次机会\n");
            return false;
        }
        if (ex == 3) {
            System.out.println("此用户存在已注册\n");
            return false;
        }
        return true;
    }
}

你可能感兴趣的:(java,java,开发语言,算法)