十七、IO流——综合练习

news2025/6/21 8:16:43

综合练习 目录

  • 一、制造假数据
    • 1.1自己写代码
    • 1.2 利用糊涂包生成假数据
  • 二、随机点名器
    • 2.1随机点名器1
    • 2.2 随机点名器2
    • 2.3 随机点名器3
    • 2.4 随机点名器4
    • 2.5 随机点名器5
  • 三、登录注册
    • 3.1 登录注册1
    • 3.2 登录注册2
    • 3.3 登录注册3


一、制造假数据

需求:制造假数据也是开发中的一个能力,在各个网上爬取数据,是其中一个方法。

在这里插入图片描述
在这里插入图片描述
https://hanyu.baidu.com/shici/detail?pid=0b2f26d4c0ddb3ee693fdb1137ee1b0d&from=kg0
男孩子取名
女孩子取名

1.1自己写代码

package Test1;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Test1 {
    public static void main(String[] args) throws IOException {
        //0.定义变量记录网址
        String famliyName = "https://hanyu.baidu.com/shici/detail?pid=0b2f26d4c0ddb3ee693fdb1137ee1b0d&from=kg0";
        String boyName = "http://www.haoming8.cn/quming/65959.html";
        String girlName = "http://www.haoming8.cn/quming/65978.html";

        //1.爬取数据,把网址上所有的数据拼接成一个字符串
        String famliyNameStr = webCrawler(famliyName);
        String boyNameStr = webCrawler(boyName);
        String girlNameStr = webCrawler(girlName);

        //2.通过正则表达式,把其中符合要求的数据获取出来
        ArrayList<String> familyNameTempList = getData(famliyNameStr, "(.{4})(,|。)", 1);
        ArrayList<String> boyNameTempList = getData(boyNameStr, "(..)(、|。)", 1);
        ArrayList<String> girlNameTempList = getData(girlNameStr, "([\\u4E00-\\u9FA5]{2})(、)", 1);

        //3.处理数据
        //3.1姓
        ArrayList<String> familyNameList = new ArrayList<>();
        for (String str : familyNameTempList) {
            for (int i = 0; i < str.length(); i++) {
                char c = str.charAt(i);
                familyNameList.add(c + "");
            }
        }

        //3.2男生姓名
        ArrayList<String> boyNameList = new ArrayList<>();
        //去重
        for (String str : boyNameTempList) {
            if (!boyNameList.contains(str)) {
                boyNameList.add(str);
            }
        }

        //3.3女生姓名
        ArrayList<String> girlNameList = new ArrayList<>();
        //去重
        for (String str : girlNameTempList) {
            if (!girlNameList.contains(str)) {
                girlNameList.add(str);
            }
        }

        //4.生成数据
        ArrayList<String> list = getInfon(familyNameList, boyNameList, girlNameList, 50, 70);

        //5.写出数据
        BufferedWriter bw = new BufferedWriter(new FileWriter("day30_code/src/Test1/name.txt"));
        for (String str : list) {
            bw.write(str);
            bw.newLine();
        }
        bw.close();

    }

    /*
     * 作用:获取男生和女生的信息
     *
     * 参数1:姓氏集合
     * 参数2:男生名集合
     * 参数3:女生名集合
     * 参数4:男生个数
     * 参数5:女生个数*/
    private static ArrayList<String> getInfon(ArrayList<String> familyNameList,
                                              ArrayList<String> boyNameList,
                                              ArrayList<String> girlNameList,
                                              int boyCount,
                                              int girlCount) {
        //0.生成男生不重复的名字
        HashSet<String> boyhs = new HashSet<>();
        while (true) {
            if (boyhs.size() == boyCount) {
                break;
            }
            //随机
            Collections.shuffle(familyNameList);
            Collections.shuffle(boyNameList);
            boyhs.add(familyNameList.get(0) + boyNameList.get(0));
        }

        //1.生成女生不重复的名字
        HashSet<String> girlhs = new HashSet<>();
        while (true) {
            if (girlhs.size() == girlCount) {
                break;
            }
            //随机
            Collections.shuffle(familyNameList);
            Collections.shuffle(girlNameList);
            girlhs.add(familyNameList.get(0) + girlNameList.get(0));
        }

        //生成最终信息
        ArrayList<String> list = new ArrayList<>();
        Random r = new Random();
        for (String boyName : boyhs) {
            //年龄:18~27
            int age = r.nextInt(10) + 18;
            list.add(boyName + "-男-" + age);
        }

        for (String girlName : girlhs) {
            //18~25
            int age = r.nextInt(7) + 18;
            list.add(girlName + "-女-" + age);
        }

        Collections.shuffle(list);
        return list;
    }

    /*
     * 作用:根据正则表达式获取字符串中的数据
     * 参数一:完整的字符串
     * 参数二:正则表达式
     * 参数三:获取匹配正则表达式中的第几组数据
     *
     * 返回值:真正想要的数据*/
    private static ArrayList<String> getData(String str, String regex, int index) {
        ArrayList<String> list = new ArrayList<>();

        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(str);
        while (matcher.find()) {
            String group = matcher.group(index);
            list.add(group);
        }
        return list;
    }

    /*
     * 作用:从网络中爬取数据,把数据拼接成字符串返回
     * 形参:网址
     * 返回值:爬取到的所有数据*/
    private static String webCrawler(String net) throws IOException {
        StringBuilder sb = new StringBuilder();

        //创建一个URL对象
        URL url = new URL(net);
        URLConnection conn = url.openConnection();

        InputStreamReader isr = new InputStreamReader(conn.getInputStream());

        int ch;
        while ((ch = isr.read()) != -1) {
            sb.append((char) ch);
        }

        isr.close();
        return sb.toString();
    }
}

1.2 利用糊涂包生成假数据

package Test1;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ReUtil;
import cn.hutool.http.HttpUtil;

import java.io.IOException;
import java.util.*;

public class HuToolTest {
    public static void main(String[] args) throws IOException {
        //0.定义变量记录网址
        String famliyName = "https://hanyu.baidu.com/shici/detail?pid=0b2f26d4c0ddb3ee693fdb1137ee1b0d&from=kg0";
        String boyName = "http://www.haoming8.cn/quming/65959.html";
        String girlName = "http://www.haoming8.cn/quming/65978.html";

        //1.请求列表页
        String familyNameStr = HttpUtil.get(famliyName);
        String boyNameStr = HttpUtil.get(boyName);
        String girlNameStr = HttpUtil.get(girlName);

        //2.利用正则表达式获取数据
        List<String> familyNameTempList = ReUtil.findAll("(.{4})(,|。)", familyNameStr, 1);
        List<String> boyNameTempList = ReUtil.findAll("(..)(、|。)", boyNameStr, 1);
        List<String> girlNameTempList = ReUtil.findAll("([\\u4E00-\\u9FA5]{2})(、)", girlNameStr, 1);

        //3.处理数据
        //3.1姓
        ArrayList<String> familyNameList = new ArrayList<>();
        for (String str : familyNameTempList) {
            for (int i = 0; i < str.length(); i++) {
                char c = str.charAt(i);
                familyNameList.add(c + "");
            }
        }

        //3.2男生姓名
        ArrayList<String> boyNameList = new ArrayList<>();
        //去重
        for (String str : boyNameTempList) {
            if (!boyNameList.contains(str)) {
                boyNameList.add(str);
            }
        }

        //3.3女生姓名
        ArrayList<String> girlNameList = new ArrayList<>();
        //去重
        for (String str : girlNameTempList) {
            if (!girlNameList.contains(str)) {
                girlNameList.add(str);
            }
        }

        //4.生成数据
        ArrayList<String> list = getInfon(familyNameList, boyNameList, girlNameList, 50, 70);

        //5.写出数据
        //糊涂包的相对路径,不是相对于当前项目而言,而是相对于class文件而言的
        FileUtil.writeLines(list,"nameOfHuTool.txt", "UTF-8");

    }
    /*
     * 作用:获取男生和女生的信息
     *
     * 参数1:姓氏集合
     * 参数2:男生名集合
     * 参数3:女生名集合
     * 参数4:男生个数
     * 参数5:女生个数*/
    private static ArrayList<String> getInfon(ArrayList<String> familyNameList,
                                              ArrayList<String> boyNameList,
                                              ArrayList<String> girlNameList,
                                              int boyCount,
                                              int girlCount) {
        //0.生成男生不重复的名字
        HashSet<String> boyhs = new HashSet<>();
        while (true) {
            if (boyhs.size() == boyCount) {
                break;
            }
            //随机
            Collections.shuffle(familyNameList);
            Collections.shuffle(boyNameList);
            boyhs.add(familyNameList.get(0) + boyNameList.get(0));
        }

        //1.生成女生不重复的名字
        HashSet<String> girlhs = new HashSet<>();
        while (true) {
            if (girlhs.size() == girlCount) {
                break;
            }
            //随机
            Collections.shuffle(familyNameList);
            Collections.shuffle(girlNameList);
            girlhs.add(familyNameList.get(0) + girlNameList.get(0));
        }

        //生成最终信息
        ArrayList<String> list = new ArrayList<>();
        Random r = new Random();
        for (String boyName : boyhs) {
            //年龄:18~27
            int age = r.nextInt(10) + 18;
            list.add(boyName + "-男-" + age);
        }

        for (String girlName : girlhs) {
            //18~25
            int age = r.nextInt(7) + 18;
            list.add(girlName + "-女-" + age);
        }

        Collections.shuffle(list);
        return list;
    }
}

二、随机点名器

2.1随机点名器1

需求:
有一个文件里面存储了班级同学的信息,每一个信息占一行。
格式为:张三-男-23
要求通过程序实现随机点名器。

在这里插入图片描述

public static void main(String[] args) throws IOException {
        /*需求:
        有一个文件里面存储了班级同学的信息,每一个信息占一行。
        格式为:张三-男-23
        要求通过程序实现随机点名器。*/

        //0.获取数据
        BufferedReader br = new BufferedReader(new FileReader("day30_code/name.txt"));
        ArrayList<String> list = new ArrayList<>();
        String line;
        while ((line = br.readLine()) != null) {
            //1.将数据添加到集合中
            list.add(line);
        }
        //释放资源
        br.close();

        //随机-点10次名
        for (int i = 0; i < 10; i++) {
            Collections.shuffle(list);
            String[] arr = list.get(0).split("-");
            System.out.println("第" + (i + 1) + "次点名: " + arr[0]);
        }
    }

2.2 随机点名器2

需求:
        一个文件里面存储了班级同学的信息,格式为:张三-男-23
        每一个学生信息占一行。
        要求通过程序实现随机点名器。
        70%的概率随机到男生
        30%的概率随机到女生
        随机100万次,统计结果。看生成男生和女生的比例是不是接近于7:3
public static void main(String[] args) throws IOException {
        /*需求:
            一个文件里面存储了班级同学的信息,格式为:张三-男-23
            每一个学生信息占一行。
            要求通过程序实现随机点名器。
            70%的概率随机到男生
            30%的概率随机到女生
            随机100万次,统计结果。看生成男生和女生的比例是不是接近于7:3*/

        //0.获取数据
        BufferedReader br = new BufferedReader(new FileReader("day30_code/name.txt"));

        //1.定义两个集合用来分别存储男生、女生的信息
        ArrayList<String> boyList = new ArrayList<>();
        ArrayList<String> girlList = new ArrayList<>();
        String line;
        while ((line = br.readLine()) != null) {
            String[] arr = line.split("-");
            if (arr[1].equals("男")) {
                boyList.add(line);
            } else {
                girlList.add(line);
            }
        }
        //释放资源
        br.close();

        //定义权重集合
        ArrayList<Integer> list = new ArrayList<>();
        Collections.addAll(list, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0);

        //随机
        Random r = new Random();
        //定义变量统计被点到的次数
        int boyCount = 0;
        int girlCount = 0;
        //循环1000000次
        for (int i = 0; i < 1000000; i++) {
            int index = r.nextInt(list.size());
            int weight = list.get(index);
            if (weight == 1) {
                //男
                Collections.shuffle(boyList);
                System.out.println(boyList.get(0));
                boyCount++;
            } else {
                //女
                Collections.shuffle(girlList);
                System.out.println(girlList.get(0));
                girlCount++;
            }
        }

        System.out.println("随机抽取100万次,其中男生被抽到了" + boyCount);
        System.out.println("随机抽取100万次,其中女生被抽到了" + girlCount);
    }

在这里插入图片描述

2.3 随机点名器3

需求:
        一个文件里面存储了班级同学的姓名,每一个姓名占一行。
        要求通过程序实现随机点名器。
        第三次必定是张三同学

      运行效果:
        第一次运行程序:随机同学姓名1
        第二次运行程序:随机同学姓名2
        第三次运行程序:张三
        …
public static void main(String[] args) throws IOException {
        /*需求:
            一个文件里面存储了班级同学的姓名,每一个姓名占一行。
            要求通过程序实现随机点名器。
            第三次必定是张三同学

            运行效果:
            第一次运行程序:随机同学姓名1
            第二次运行程序:随机同学姓名2
            第三次运行程序:张三
                …*/
        //0.读取数据
        BufferedReader br = new BufferedReader(new FileReader("day30_code/name.txt"));
        ArrayList<String> nameList = new ArrayList<>();
        String line;
        while ((line = br.readLine()) != null) {
            nameList.add(line);
        }
        br.close();

        //2.读取当前程序已经运行的次数
        BufferedReader br1 = new BufferedReader(new FileReader("day30_code/count.txt"));
        String countStr = br1.readLine();
        int count = Integer.parseInt(countStr);

        //3.程序没运行一次count+1
        count++;

        //判断
        if (count == 3){
            System.out.println("张三");
        } else {
            //点名
            Collections.shuffle(nameList);
            String[] arr = nameList.get(0).split("-");
            System.out.println(arr[0]);

        }
        System.out.println(count);

        //将count写入文件中
        BufferedWriter bw = new BufferedWriter(new FileWriter("day30_code/count.txt"));
        bw.write(count+"");
        bw.close();
    }

2.4 随机点名器4

需求:
        一个文件里面存储了班级同学的姓名,每一个姓名占一行。
        要求通过程序实现随机点名器。

      运行结果要求:
        被点到的学生不会再被点到。
        但是如果班级中所有的学生都点完了, 需要重新开启第二轮点名。

      核心思想:
           点一个删一个,把删除的备份,全部点完时还原数据。
package Test2;

import java.io.*;
import java.util.ArrayList;
import java.util.Collections;

public class Test5 {
    public static void main(String[] args) throws IOException {
        /*需求:
            一个文件里面存储了班级同学的姓名,每一个姓名占一行。
            要求通过程序实现随机点名器。

          运行结果要求:
            被点到的学生不会再被点到。
            但是如果班级中所有的学生都点完了, 需要重新开启第二轮点名。

          核心思想:
               点一个删一个,把删除的备份,全部点完时还原数据。
               */

        //定义变量,表示初始文件路径
        String src = "day30_code/name.txt";
        //定义变量,表示备份文件,一开始文件为空
        String backups = "day30_code/src/Test2/backups.txt";

        //测试点名121次
        for (int i = 0; i < 121; i++) {
            //获取数据并将其装入集合中
            ArrayList<String> list = readFile(src);

            //判断集合中是否有数据
            if (list.size() == 0) {
                //如果没有数据,表示所有学生已经点完,从backups.txt中还原数据即可
                list = readFile(backups);
                //把所有数据都写到初始文件中
                writeFile(src, list, false);
                //删除备份数据
                new File(backups).delete();
            }

            //点名-点一个删一个
            Collections.shuffle(list);
            String stuInfo = list.remove(0);
            System.out.println("被点名的学生是:"+stuInfo);
            //把删除之后的所有学生写到初始文件中
            writeFile(src,list,false);
            writeFile(backups,stuInfo, true);//追加写入
        }

    }

    private static void writeFile(String pathFile, String str, boolean isAppend) throws IOException {
        BufferedWriter bw = new BufferedWriter(new FileWriter(pathFile, isAppend));
        bw.write(str);
        bw.newLine();
        bw.close();
    }

    private static void writeFile(String pathFile, ArrayList<String> list, boolean isAppend) throws IOException {
        BufferedWriter bw = new BufferedWriter(new FileWriter(pathFile, isAppend));
        for (String str : list) {
            bw.write(str);
            bw.newLine();
        }
        bw.close();
    }

    private static ArrayList<String> readFile(String pathFile) throws IOException {
        ArrayList<String> list = new ArrayList<>();
        BufferedReader br = new BufferedReader(new FileReader(pathFile));
        String line;
        while ((line = br.readLine()) != null) {
            list.add(line);
        }
        br.close();
        return list;
    }
}


2.5 随机点名器5

在这里插入图片描述
在这里插入图片描述

在这里插入图片描述
数据准备
钦逸抒-女-21-0.5
屈燕妮-女-24-1.0
阴诗雁-女-25-1.0
伯荷燕-女-24-1.0
欧文新-男-20-0.5
董泽欧-男-18-1.0
滕星磊-男-18-1.0
阚晴岚-女-22-1.0
傅彬远-男-19-1.0
左花依-女-24-0.25

package Test3;

import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;

public class Test4 {
    public static void main(String[] args) throws IOException {
        //0.获取学生信息
        ArrayList<Student> list = new ArrayList<>();
        BufferedReader br = new BufferedReader(new FileReader("day30_code/src/Test3/names.txt"));
        String line;
        while ((line = br.readLine()) != null) {
            String[] arr = line.split("-");
            Student stu = new Student(arr[0], arr[1], Integer.parseInt(arr[2]), Double.parseDouble(arr[3]));
            list.add(stu);
        }
        br.close();
        //计算总权重
        double weight = 0;
        for (Student stu : list) {
            weight += stu.getWeight();
        }

        //计算每一个人的权重占比
        double[] arr = new double[list.size()];
        int index = 0;
        for (Student s : list) {
            arr[index] = s.getWeight() / weight;
            index++;
        }

        //计算每一个人的权重占比范围
        for (int i = 1; i < arr.length; i++) {
            arr[i] = arr[i] + arr[i - 1];
        }
        System.out.println(Arrays.toString(arr));

        //随机抽取
        double num = Math.random();
        //判断位置-二分查找
        int res = -Arrays.binarySearch(arr, num) - 1;

        Student stu = list.get(res);
        System.out.println(stu);

        //修改当前学生的权重
        double w = stu.getWeight() / 2;
        stu.setWeight(w);

        //将数据写入文件中
        BufferedWriter bw = new BufferedWriter(new FileWriter("day30_code/src/Test3/names.txt"));
        for (Student s : list) {
            bw.write(s.toString());
            bw.newLine();
        }
        bw.close();


    }
}

三、登录注册

3.1 登录注册1

需求:写一个登陆小案例。

    步骤:
        将正确的用户名和密码手动保存在本地的userinfo.txt文件中。
        保存格式为:username=zhangsan&password=123
        让用户键盘录入用户名和密码
                比较用户录入的和正确的用户名密码是否一致
        如果一致则打印登陆成功
                如果不一致则打印登陆失败
package Test4;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;

public class Test4 {
    public static void main(String[] args) throws IOException {
        /*需求:写一个登陆小案例。

        步骤:
            将正确的用户名和密码手动保存在本地的userinfo.txt文件中。
            保存格式为:username=zhangsan&password=123
            让用户键盘录入用户名和密码
                    比较用户录入的和正确的用户名密码是否一致
            如果一致则打印登陆成功
                    如果不一致则打印登陆失败*/

        //0.获取数据
        BufferedReader br = new BufferedReader(new FileReader("day30_code\\src\\Test4\\userinfo.txt"));
        String line = br.readLine();
        br.close();

        //1.处理数据
        String[] arr = line.split("&");
        //用户名
        String[] arr1 = arr[0].split("=");
        String rightUserName = arr1[1];
        //密码
        String[] arr2 = arr[1].split("=");
        String rightPassword = arr2[1];

        //用户输入用户名和密码
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入用户名:");
        String userName = sc.nextLine();
        System.out.println("请输入密码:");
        String passwd = sc.nextLine();

        //判断
        if (userName.equals(rightUserName) && passwd.equals(rightPassword)) {
            System.out.println("登录成功~");
        } else {
            System.out.println("登录失败~");
        }
    }
}

3.2 登录注册2

需求:写一个登陆小案例(添加锁定账号功能)

    步骤:
    	将正确的用户名和密码手动保存在本地的userinfo.txt文件中。
    	保存格式为:username=zhangsan&password=123&count=0
    	让用户键盘录入用户名和密码
    	比较用户录入的和正确的用户名密码是否一致
    	如果一致则打印登陆成功
    	如果不一致则打印登陆失败,连续输错三次被锁定
public static void main(String[] args) throws IOException {
        /*需求:写一个登陆小案例(添加锁定账号功能)

        步骤:
        	将正确的用户名和密码手动保存在本地的userinfo.txt文件中。
        	保存格式为:username=zhangsan&password=123&count=0
        	让用户键盘录入用户名和密码
        	比较用户录入的和正确的用户名密码是否一致
        	如果一致则打印登陆成功
        	如果不一致则打印登陆失败,连续输错三次被锁定*/

        //0.获取数据
        BufferedReader br = new BufferedReader(new FileReader("day30_code\\src\\Test5\\userinfo.txt"));
        String line = br.readLine();
        br.close();

        //1.处理数据
        String[] arr = line.split("&");
        String rightUserName = arr[0].split("=")[1];
        String rightPasswd = arr[1].split("=")[1];
        String countStr = arr[2].split("=")[1];
        int count = Integer.parseInt(countStr);


        //2.用户输入数据
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入用户名:");
        String username = sc.nextLine();
        System.out.println("请输入密码:");
        String passwd = sc.nextLine();

        //3.判断用户名/密码是否正确
        if (rightUserName.equals(username) && rightPasswd.equals(passwd)) {
            //判断count是否大于3,是 则提示账号已经被锁定,终止程序运行
            if (count > 3) {
                System.out.println("当前账号已经被锁定,请联系管理员!");
                System.exit(0);
            }
            System.out.println("登录成功~");
            writeInfo("username=zhangsan&password=123&count=0");

        } else {
            count++;
            if (count < 3) {
                System.out.println("登录失败,还剩下" + (3 - count) + "次机会~");
            } else {
                System.out.println("用户账号被锁定!");
            }
            writeInfo("username=zhangsan&password=123&count=" + count);
        }
    }

    private static void writeInfo(String content) throws IOException {
        BufferedWriter bw = new BufferedWriter(new FileWriter("day30_code\\src\\Test5\\userinfo.txt"));
        bw.write(content);
        bw.newLine();
        bw.close();
    }

3.3 登录注册3

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
斗地主综合项目链接

获取用户信息:

private void readUserInfo() {
        List<String> userInfoList = FileUtil.readUtf8Lines("G:\\code\\Java\\basic_code\\puzzlegame\\userinfo.txt");
        for (String str : userInfoList) {
            String[] arr = str.split("&");
            String[] arr1 = arr[0].split("=");
            String[] arr2 = arr[1].split("=");

            User u =new User(arr1[1],arr2[1]);
            allUsers.add(u);
        }

        System.out.println(allUsers);
    }

在这里插入图片描述
在这里插入图片描述

public void mouseClicked(MouseEvent e) {
        if (e.getSource() == submit) {
            //点击了注册按钮

            //0.用户名,密码不能为空
            if (username.getText().length() == 0 || password.getText().length() == 0 || rePassword.getText().length() == 0) {
                showDialog("用户名和密码不能为空");
                return;
            }

            //1.判断两次密码输入是否一致
            if (!password.getText().equals(rePassword.getText())) {
                showDialog("两次密码输入不一致");
                return;
            }

            //2.判断用户名和密码的格式是否正确
            if (!username.getText().matches("[a-zA-Z0-9]{4,16}")) {
                showDialog("用户名格式不正确,必须是4~16位");
                return;
            }

            if (!password.getText().matches("\\S*(?=\\S{6,})(?=\\S*\\d)(?=\\S*[A-Z])(?=\\S*[a-z])\\S*")) {
                showDialog("密码格式不正确,最少六位,至少包含一个大写字母,一个小写字母!");
                return;
            }

            //3.判断用户名是否已经重复
            if (containsUserName(username.getText())){
                showDialog("用户名已经存在,请重新输入");
                return;
            }
            //4.添加用户
            allUsers.add(new User(username.getText(),password.getText()));

            //5.写入文件
            FileUtil.writeLines(allUsers,"G:\\code\\Java\\basic_code\\puzzlegame\\userinfo.txt","UTF-8");

            //6.提示注册成功
            showDialog("注册成功!");
            this.setVisible(false);
            new LoginJFrame();

        } else if (e.getSource() == reset) {
            //点击了重置按钮
            //清空三个输入框
            username.setText("");
            password.setText("");
            rePassword.setText("");
        }
    }
    /*作用:
     *       判断username在集合中是否存在
     * 参数:
     *       用户名
     * 返回值:
     *       true:存在
     *       false:不存在*/
    private boolean containsUserName(String username) {
        for (User u : allUsers) {
            if (u.getUsername().equals(username)){
                return true;
            }
        }
        return false;
    }

在这里插入图片描述

在这里插入图片描述
在这里插入图片描述

//获取当前是哪个存档被点击了,获取其中的序号
            JMenuItem item = (JMenuItem) obj;
            String str = item.getText();
            int index = str.charAt(2) - '0';

            //直接把游戏的数据写到本地文件中
            try {
                ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("puzzlegame\\save\\save" + index + ".data"));
                GameInfo gi = new GameInfo(data, x, y, path, step);
                IoUtil.writeObj(oos, true, gi);
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
            //修改一下存档item上的展示信息
            //存档0(XX步)
            item.setText("存档" + index + "(" + step + "步)");
            //修改一下读档item上的展示信息
            loadJMenu.getItem(index).setText("存档" + index + "(" + step + "步)");

读档:

else if (obj == saveItem0 || obj == saveItem1 || obj == saveItem2 || obj == saveItem3 || obj == saveItem4) {
            //获取当前是哪个存档被点击了,获取其中的序号
            JMenuItem item = (JMenuItem) obj;
            String str = item.getText();
            int index = str.charAt(2) - '0';

            //直接把游戏的数据写到本地文件中
            try {
                ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("puzzlegame\\save\\save" + index + ".data"));
                GameInfo gi = new GameInfo(data, x, y, path, step);
                IoUtil.writeObj(oos, true, gi);
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
            //修改一下存档item上的展示信息
            //存档0(XX步)
            item.setText("存档" + index + "(" + step + "步)");
            //修改一下读档item上的展示信息
            loadJMenu.getItem(index).setText("存档" + index + "(" + step + "步)");
        } else if (obj == loadItem0 || obj == loadItem1 || obj == loadItem2 || obj == loadItem3 || obj == loadItem4) {
            //获取当前是哪个读档被点击了,获取其中的序号
            JMenuItem item = (JMenuItem) obj;
            String str = item.getText();
            int index = str.charAt(2) - '0';

            GameInfo gi = null;
            try {
                //可以到本地文件中读取数据
                ObjectInputStream ois = new ObjectInputStream(new FileInputStream("puzzlegame\\save\\save" + index + ".data"));
                gi = (GameInfo)ois.readObject();
                ois.close();
            } catch (IOException ioException) {
                ioException.printStackTrace();
            } catch (ClassNotFoundException classNotFoundException) {
                classNotFoundException.printStackTrace();
            }

            data = gi.getData();
            path = gi.getPath();
            step = gi.getStep();
            x = gi.getX();
            y = gi.getY();

            //重新刷新界面加载游戏
            initImage();



        }

public void getGameInfo(){
        //1.创建File对象表示所有存档所在的文件夹
        File file = new File("puzzlegame\\save");
        //2.进入文件夹获取到里面所有的存档文件
        File[] files = file.listFiles();
        //3.遍历数组,得到每一个存档
        for (File f : files) {
            //f :依次表示每一个存档文件
            //获取每一个存档文件中的步数
            GameInfo gi = null;
            try {
                ObjectInputStream ois = new ObjectInputStream(new FileInputStream(f));
                gi = (GameInfo)ois.readObject();
                ois.close();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
            //获取到了步数
            int step = gi.getStep();

            //把存档的步数同步到菜单当中
            //save0 ---> 0
            //save1 ---> 1
            //...

            //获取存档的文件名 save0.data
            String name = f.getName();
            //获取当存档的序号(索引)
            int index = name.charAt(4) - '0';
            //修改菜单上所表示的文字信息
            saveJMenu.getItem(index).setText("存档" + index + "(" + step + ")步");
            loadJMenu.getItem(index).setText("存档" + index + "(" + step + ")步");
        }

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1503266.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

BadUsb制作

BadUsb制作 一个树莓派pico kali监听 需要的文件 https://pan.baidu.com/s/1_kyzXIqk9JWHGHstTgq7sQ?pwd6666 1.将pico插入电脑 2.将Bad USB固件中的文件复制到pico中&#xff0c;pico会重启 3.将Bad USB目录文件复制进去&#xff08;打开Bad USB目录文件复制&#xff09; …

MySQL--explain执行计划详解

什么是执行计划&#xff1f; SQL的执行计划&#xff0c;通俗来说就是SQL的执行情况&#xff0c;一条SQL语句扫描哪些表&#xff0c;那个子查询先执行&#xff0c;是否用到了索引等等&#xff0c;只有当我们知道了这些情况之后才知道&#xff0c;才可以更好的去优化SQL&#xf…

如何将MathType嵌入到word中 word打开MathType显示错误

当我们编辑好mathtype公式以后&#xff0c;有时候需要将这个公式导入到word中&#xff0c;但是有不少用户们不清楚mathtype如何嵌入到word中。今天小编就给大家说明一下mathtype公式导入word的两种不同方法&#xff0c;有需要的用户们赶紧来看一下吧。 一、mathtype如何嵌入到…

(产品之美系列三)小红书投票组建,利用用户好奇心,增大互动

小红书发布笔记或者视频&#xff0c;可以带一个投票功能。此投票功能与其他的有什么不同呢&#xff1f; 发布一个话题:你觉得王维和李白哪个更帅&#xff1f; 如果你自己不投票&#xff0c;就是看不到结果。当你投票之后: 可以知道选择王维的有百分之八十二。 启发:小红书投…

Git分布式管理-头歌实验远程版本库

Git的一大特点就是&#xff0c;能为不同系统下的开发者提供了一个协作开发的平台。而团队如果要基于Git进行协同开发&#xff0c;就必须依赖远程版本库。远程版本库允许&#xff0c;我们将本地版本库保存在远端服务器&#xff0c;而且&#xff0c;不同的开发者也是基于远程版本…

OJ:循环队列

622. 设计循环队列 - 力扣&#xff08;LeetCode&#xff09; 思路 思路&#xff1a;首先循环队列的意思是&#xff1a;空间固定&#xff0c;就是提前开辟好&#xff0c;满了就不能插入了&#xff0c;但是删除数据后仍有空间&#xff0c;删除循环队列里面的数据后&#xff0c;保…

Python学习日记之学习turtle库(上 篇)

一、初步认识turtle库 turtle 库是 Python 语言中一个很流行的绘制图像的函数库&#xff0c;想象一个小乌龟&#xff0c;在一个横 轴为 x、纵轴为 y 的坐标系原点&#xff0c;(0,0)位置开始&#xff0c;它根据一组函数指令的控制&#xff0c;在这个平面 坐标系中移动&#xff0…

如果编程语言是一种武器……

对程序员来说&#xff0c;编程语言就是武器&#xff0c;但有的武器好用&#xff0c;有的武器不好用&#xff0c;有的武器甚至会杀了自己 C语言是M1式加兰德步枪&#xff0c;很老但可靠。 C是双截棍&#xff0c;挥舞起来很强悍&#xff0c;很吸引人&#xff0c;但需要你多年的磨…

Ubuntu平铺左、右、上、下、1/2、1/4窗口(脚本)

前言 之前因为一直在用Ubuntu 18或者Ubuntu 20然后发现装了GNOME插件后&#xff0c;电脑在使用过程中&#xff0c;会时不时的卡死&#xff08;鼠标没问题&#xff0c;键盘输入会有10-20秒的延迟&#xff09;频率基本是一小时一次&#xff0c;因为这种卡顿会很容易打断思路&…

攻防世界-MISC-EASY_EVM

题目链接&#xff1a;攻防世界 (xctf.org.cn) 下载附件得到info.txt&#xff1a; pragma solidity ^0.5.0; ABI: [ { "inputs": [], "payable": true, "stateMutability": "payable", "type": "constructor" }, {…

基于单片机的RFID门禁系统设计

目 录 摘 要 I Abstract II 引 言 1 1 控制系统设计 3 1.1 主控制器选择 3 1.2 项目总体设计 3 2 项目硬件设计 5 2.1 单片机控制模块 5 2.2 射频识别模块 8 2.3 矩阵键盘模块 9 2.4 液晶显示模块 10 2.5 报警模块 11 2.6 AT24C02存储模块 12 2.7 继电器驱动模块 13 2.8 总电路…

【ubuntu】安装 Anaconda3

目录 一、Anaconda 说明 二、操作记录 2.1 下载安装包 2.1.1 官网下载 2.1.2 镜像下载 2.2 安装 2.2.1 安装必要的依赖包 2.2.2 正式安装 2.2.3 检测是否安装成功 方法一 方法二 方法三 2.3 其他 三、参考资料 3.1 安装资料 3.2 验证是否成功的资料 四、其他 …

数据结构之八大排序

&#x1d649;&#x1d65e;&#x1d658;&#x1d65a;!!&#x1f44f;&#x1f3fb;‧✧̣̥̇‧✦&#x1f44f;&#x1f3fb;‧✧̣̥̇‧✦ &#x1f44f;&#x1f3fb;‧✧̣̥̇:Solitary_walk ⸝⋆ ━━━┓ - 个性标签 - &#xff1a;来于“云”的“羽球人”。…

数列操作1——栈+前缀和,典型例题,值得一看

题目描述 先给定一个长度为n数列&#xff0c;再给定m个操作&#xff0c;现在需要维护五个操作&#xff1a; 1 x&#xff1a;在光标的前面插入一个数字x。 2&#xff1a;删除光标前的最后一个数字&#xff0c;如果光标前没有数字则忽略。 3&#xff1a;左移一格光标&#xf…

【Python】7. 基础语法(5) -- 文件+库+习题篇

文件 文件是什么 变量是把数据保存到内存中. 如果程序重启/主机重启, 内存中的数据就会丢失. 要想能让数据被持久化存储, 就可以把数据存储到硬盘中. 也就是在 文件 中保存 在 Windows “此电脑” 中, 看到的内容都是 文件. 文件夹(目录)也是一种特殊的文件->目录文件 通过…

关于装载类子系统

装载类子系统 类加载器字节码调节器类加载运行时数据区 类加载器 将class文件加载进jvm的方法去&#xff0c;并在方法去中创建一个java.lang.Class对象作为外界访问这个类的接口。实现这个动作的代码模块称为类加载器。 类加载器分类 启动类加载器&#xff08;Bootstrap C…

qt带后缀单位的QLineEdit

QLineEditUnit.h #pragma once #include <QLineEdit> #include <QPushButton>class QLineEditUnit : public QLineEdit {Q_OBJECT public:QLineEditUnit(QWidget* parent Q_NULLPTR);~QLineEditUnit();//获取编辑框单位QString UnitText()const;//设置编辑框单位…

ubuntu自带屏幕截图功能

目录 简介开始截屏步骤1.打开截屏软件2.选择区域3.截图 快捷键 录屏方法11.开始录屏2.停止录屏 方法2 补充说明 简介 试了好多开源跨平台截图软件&#xff0c;但是在ubuntu上都或多或少存在问题。ubuntu有自带的截图软件。打算把ubuntu自带的截图软件用起来。 顺便说一下我使…

JavaScript数组方法常用方法大全

提示&#xff1a;文章写完后&#xff0c;目录可以自动生成&#xff0c;如何生成可参考右边的帮助文档 文章目录 1. push()2. pop()3. unshift()4. shift()5. isArray()6. map()7. filter()8. every()9. some()10. splice()11. slice()12. indexOf()13. includes()14. concat()1…

Vue+SpringBoot打造木马文件检测系统

目录 一、摘要1.1 项目介绍1.2 项目录屏 二、功能模块2.1 数据中心模块2.2 木马分类模块2.3 木马软件模块2.4 安全资讯模块2.5 脆弱点模块2.6 软件检测模块 三、系统设计3.1 用例设计3.2 数据库设计3.2.1 木马分类表3.2.2 木马软件表3.2.3 资讯表3.2.4 脆弱点表3.2.5 软件检测表…