javase复习day30综合练习

devtools/2024/9/23 0:29:57/

制造假数据

制造数据

练习一

package Demo1;import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;public class Demo1 {public static void main(String[] args) throws IOException {//爬取数据//获取链接/*制造假数据:获取姓氏:https://hanyu.baidu.com/shici/detail?pid=0b2f26d4c0ddb3ee693fdb1137ee1b0d&from=kg0获取男生名字:http://www.haoming8.cn/baobao/10881.html获取女生名字:http://www.haoming8.cn/baobao/7641.html*///1.定义变量记录网址String familyNameNet = "https://hanyu.baidu.com/shici/detail?pid=0b2f26d4c0ddb3ee693fdb1137ee1b0d&from=kg0";String boyNameNet = "http://www.haoming8.cn/baobao/10881.html";String girlNameNet = "http://www.haoming8.cn/baobao/7641.html";//2.爬取数据,把网址上所有的数据拼接成一个字符串String familyNameStr = webCrawler(familyNameNet);System.out.println(familyNameStr);String boyNameStr = webCrawler(boyNameNet);String girlNameStr = webCrawler(girlNameNet);//        将爬取到的数据使用正则表达式进行筛选ArrayList<String> familyNameTempList = getData(familyNameStr,"(.{4})(,|。)",1);ArrayList<String> boyNameTempList = getData(boyNameStr,"([\\u4E00-\\u9FA5]{2})(、|。)",1);ArrayList<String> girlNameTempList = getData(girlNameStr,"(.. ){4}..",0);
//        System.out.println(familyNameTempList.toString());
//        System.out.println("===============================================================");
//        System.out.println(boyNameTempList.toString());
//        System.out.println("==============================================================");
//        System.out.println(girlNameTempList.toString());//处理获取的数据//处理姓氏//处理方案:每个集合拆成char数据进行写入ArrayList<String> familyNameList = new ArrayList<>();for (String s : familyNameTempList) {for (int i = 0; i < 4; i++) {familyNameList.add(s.charAt(i)+"");}}//处理男名字//处理方案:去重ArrayList<String> boyNameList = new ArrayList<>();for (String s : boyNameTempList) {if (!boyNameList.contains(s)){boyNameList.add(s);}}//处理女名字//处理方案:拆fenArrayList<String> girlNameList = new ArrayList<>();for (String s : girlNameTempList) {String[] split = s.split(" ");for (int i = 0; i < split.length; i++) {girlNameList.add(split[i]);}}//创建数据/*** 姓名(唯一)-性别-年龄*/ArrayList<String> namelist = getData(familyNameList, boyNameList, girlNameList, 70, 40);System.out.println(namelist.toString());//写出数据BufferedWriter bw = new BufferedWriter(new FileWriter("a\\sd\\scs\\a.txt"));int a;for (String s : namelist) {bw.write(s);bw.nexyLine();}bw.close();}public static ArrayList<String> getData(ArrayList<String> familyNameList,ArrayList<String> boyNameList,ArrayList<String> girlNameList,int boyname,int girlbame){//男名字HashSet<String> boyset = new HashSet<>();while (true){if (boyset.size() == boyname){break;}Collections.shuffle(familyNameList);Collections.shuffle(boyNameList);boyset.add(familyNameList.get(0)+boyNameList.get(0));}//女名字HashSet<String> grilset = new HashSet<>();while (true){if (grilset.size() == girlbame){break;}Collections.shuffle(familyNameList);Collections.shuffle(girlNameList);grilset.add(familyNameList.get(0)+girlNameList.get(0));}ArrayList<String> namelist = new ArrayList<>();Random r = new Random();for (String s : boyset) {int i = r.nextInt(10)+18;namelist.add(s+"-男-"+i);}for (String s : grilset) {int i = r.nextInt(8)+18;namelist.add(s+"-女-"+i);}return  namelist;}/***     * 作用:根据正则表达式获取字符串中的数据*     * 参数一:*     *       完整的字符串*     * 参数二:*     *       正则表达式*     * 参数三:*     *      获取数据*     *       0:获取符合正则表达式所有的内容*     *       1:获取正则表达式中第一组数据*     *       2:获取正则表达式中第二组数据*     *       ...以此类推*     **     * 返回值:*     *       真正想要的数据* 将爬取的数据进行筛选* @param str 爬取的数据* @param s 正则表达式* @param i 正则表达式筛选后保存的位置* @return*/private static ArrayList<String> getData(String str, String s, int i) {//使用正则表达式筛选//创建集合保存数据ArrayList<String> list = new ArrayList<>();Pattern p=Pattern.compile(s);Matcher matcher=p.matcher(str);if(matcher.find()){System.out.println(matcher.group(i));list.add(matcher.group(i));}return list;}/*** 爬取网站返回网站的数据
//     * @param  网站地址* @return*/private static String webCrawler(String src) throws IOException {//创建网站的流//记录读取的数据StringBuilder sb = new StringBuilder();//创建URL对象URL url = new URL(src);//使用URL创建网络连接URLConnection urlConnection = url.openConnection();//将网络连接交给InputStreamReader对象进行数据操作InputStreamReader isr = new InputStreamReader(urlConnection.getInputStream());//读取数据将数据交给StringBuilder进行记录int ch;while ((ch = isr.read()) != -1){sb.append((char)ch);}//关闭流isr.close();return sb.toString();}}
使用hutools包进行的爬取
public class Demo2 {public static void main(String[] args) throws IOException {//爬取数据//获取链接/*制造假数据:获取姓氏:https://hanyu.baidu.com/shici/detail?pid=0b2f26d4c0ddb3ee693fdb1137ee1b0d&from=kg0获取男生名字:http://www.haoming8.cn/baobao/10881.html获取女生名字:http://www.haoming8.cn/baobao/7641.html*///1.定义变量记录网址String familyNameNet = "https://hanyu.baidu.com/shici/detail?pid=0b2f26d4c0ddb3ee693fdb1137ee1b0d&from=kg0";String boyNameNet = "http://www.haoming8.cn/baobao/10881.html";String girlNameNet = "http://www.haoming8.cn/baobao/7641.html";//2.爬取数据,把网址上所有的数据拼接成一个字符串String familyNameStr = HttpUtil.get(familyNameNet);String boyNameStr = HttpUtil.get(boyNameNet);String girlNameStr =  HttpUtil.get(girlNameNet);//        将爬取到的数据使用正则表达式进行筛选ArrayList<String> familyNameTempList = (ArrayList<String>) ReUtil.findAll("(.{4})(,|。)",familyNameStr,1);ArrayList<String> boyNameTempList = (ArrayList<String>) ReUtil.findAll("([\\u4E00-\\u9FA5]{2})(、|。)",boyNameStr,1);ArrayList<String> girlNameTempList = (ArrayList<String>) ReUtil.findAll("(.. ){4}..",girlNameStr,0);//处理获取的数据//处理姓氏//处理方案:每个集合拆成char数据进行写入ArrayList<String> familyNameList = new ArrayList<>();for (String s : familyNameTempList) {for (int i = 0; i < 4; i++) {familyNameList.add(s.charAt(i)+"");}}//处理男名字//处理方案:去重ArrayList<String> boyNameList = new ArrayList<>();for (String s : boyNameTempList) {if (!boyNameList.contains(s)){boyNameList.add(s);}}//处理女名字//处理方案:拆fenArrayList<String> girlNameList = new ArrayList<>();for (String s : girlNameTempList) {String[] split = s.split(" ");for (int i = 0; i < split.length; i++) {girlNameList.add(split[i]);}}//创建数据/*** 姓名(唯一)-性别-年龄*/ArrayList<String> namelist = getData(familyNameList, boyNameList, girlNameList, 70, 40);Collections.shuffle(namelist);//写出数据FileUtil.writeLines(namelist,"C:\\Users\\20724\\Desktop\\name.txt","UTF-8");}public static ArrayList<String> getData(ArrayList<String> familyNameList,ArrayList<String> boyNameList,ArrayList<String> girlNameList,int boyname,int girlbame){//男名字HashSet<String> boyset = new HashSet<>();while (true){if (boyset.size() == boyname){break;}Collections.shuffle(familyNameList);Collections.shuffle(boyNameList);boyset.add(familyNameList.get(0)+boyNameList.get(0));}//女名字HashSet<String> grilset = new HashSet<>();while (true){if (grilset.size() == girlbame){break;}Collections.shuffle(familyNameList);Collections.shuffle(girlNameList);grilset.add(familyNameList.get(0)+girlNameList.get(0));}ArrayList<String> namelist = new ArrayList<>();Random r = new Random();for (String s : boyset) {int i = r.nextInt(10)+18;namelist.add(s+"-男-"+i);}for (String s : grilset) {int i = r.nextInt(8)+18;namelist.add(s+"-女-"+i);}return  namelist;}}

随机点名器

练习一:

public class Test1 {public static void main(String[] args) throws IOException {//"C:\\Users\\20724\\Desktop\\name.txt","UTF-8"//创建读取流BufferedReader br = new BufferedReader(new FileReader("C:\\Users\\20724\\Desktop\\name.txt"));//读取的数据使用list集合进行存储ArrayList<String> list = new ArrayList<>();String str;while ((str = br.readLine()) != null){list.add(str);}br.close();//随机数获取要的名字Random r = new Random();int index = r.nextInt(list.size());String s = list.get(index);System.out.println("选中的同学的名字为:"+s.split("-")[0]);}
}

练习二:

public class Test2 {public static void main(String[] args) throws IOException {//"C:\\Users\\20724\\Desktop\\name.txt","UTF-8"//创建读取流BufferedReader br = new BufferedReader(new FileReader("C:\\Users\\20724\\Desktop\\name.txt"));//读取的数据使用list集合进行存储ArrayList<String> list = new ArrayList<>();String str;while ((str = br.readLine()) != null){list.add(str);}br.close();for (int i = 0; i < 1000000; i++) {String name =  RannderName(br,list);System.out.println(name);}}private static String RannderName(BufferedReader br,ArrayList<String> list) throws IOException {//随机数获取要的名字Random r = new Random();//随机数确定要的是男还是女int inderSex = r.nextInt(10)+1;String s;if (inderSex<=7){while (true) {//抽男生int index = r.nextInt(list.size());s = list.get(index);//判断是否为男生String[] split = s.split("-");if (split[1].equals("男")){//是男生break;}}}else {while (true) {//抽男生int index = r.nextInt(list.size());s = list.get(index);//判断是否为女生String[] split = s.split("-");if (split[1].equals("女")){//是女生break;}}}String name = "选中的同学的名字为:"+s;return name;}}

练习三:

public class Test3 {public static void main(String[] args) throws IOException {//"C:\\Users\\20724\\Desktop\\name.txt","UTF-8"//创建读取流BufferedReader br = new BufferedReader(new FileReader("C:\\Users\\20724\\Desktop\\name.txt"));//读取的数据使用list集合进行存储ArrayList<String> list = new ArrayList<>();String str;while ((str = br.readLine()) != null){list.add(str);}br.close();//将运行次数存入文件,每次运行时读取判断是第几次运行//读取文件BufferedReader Runnum = new BufferedReader(new FileReader("C:\\Users\\20724\\Desktop\\demo\\javase2day01\\javaseday30\\a.txt"));String s1 = Runnum.readLine();Runnum.close();int i = Integer.parseInt(s1);if (i==3){//显示张三并将文件加一System.out.println("选中的同学的名字为:张三");//写入数据int n = i+1;BufferedWriter bw = new BufferedWriter(new FileWriter("C:\\Users\\20724\\Desktop\\demo\\javase2day01\\javaseday30\\a.txt"));bw.write(n+"");bw.close();return;}//随机数获取要的名字Random r = new Random();int index = r.nextInt(list.size());String s = list.get(index);System.out.println("选中的同学的名字为:"+s.split("-")[0]);//写入数据int n = i+1;BufferedWriter bw = new BufferedWriter(new FileWriter("C:\\Users\\20724\\Desktop\\demo\\javase2day01\\javaseday30\\a.txt"));bw.write(n+"");bw.close();}
}

练习四:

public class Test4 {public static void main(String[] args) throws IOException {//"C:\\Users\\20724\\Desktop\\name.txt","UTF-8"//创建读取流,两个读取流每次运行将这两个都读取出来BufferedReader br = new BufferedReader(new FileReader("C:\\Users\\20724\\Desktop\\name.txt"));BufferedReader Runnum = new BufferedReader(new FileReader("C:\\Users\\20724\\Desktop\\demo\\javase2day01\\javaseday30\\b.txt"));//读取的数据使用list集合进行存储ArrayList<String> list = new ArrayList<>();ArrayList<String> next = new ArrayList<>();String str;while ((str = br.readLine()) != null){list.add(str);}br.close();String str2;while ((str2 = Runnum.readLine()) != null){next.add(str2);}Runnum.close();//先进行判断是否已经读取一轮if (list.size()==next.size()){//清空已选文件BufferedWriter bw = new BufferedWriter(new FileWriter("C:\\Users\\20724\\Desktop\\demo\\javase2day01\\javaseday30\\b.txt"));bw.close();return;}Random r = new Random();//获取的名字String s;//随机数获取要的名字while (true) {int index = r.nextInt(list.size());s = list.get(index);//判断已选文件中有没有这个名字if (next.contains(s)){continue;}System.out.println("选中的同学的名字为:"+s.split("-")[0]);break;}//写入数据BufferedWriter writer = new BufferedWriter(new FileWriter("C:\\Users\\20724\\Desktop\\demo\\javase2day01\\javaseday30\\b.txt", true));writer.write(s);writer.newLine();writer.close();}
}

练习五:

public class Demo5 {public static void main(String[] args) throws IOException {//带权重的随机BufferedReader br = new BufferedReader(new FileReader("javaseday30\\a.txt"));//将数据存入Student对象存入集合中ArrayList<Student> list = new ArrayList<>();String str;while ((str = br.readLine()) != null){String[] split = str.split("-");Student student = new Student(split[0],split[1],Integer.parseInt(split[2]),Double.parseDouble(split[3]));list.add(student);}br.close();//获取总的权重和double weight = 0;for (Student student : list) {weight += student.getWeight();}//计算每个对象的权重,并存入数组中double[] arr= new double[list.size()];int count = 0;for (Student student : list) {arr[count] = student.getWeight()/weight;count++;}//计算各个区间的数据for (int i = 1; i < arr.length; i++) {arr[i] = arr[i] + arr[i-1];}//进行随机得到0-1之间的随机数double random = Math.random();
//        System.out.println(random);//判断random在arr 中的位置//使用二分法查找,使用Arrays.binarySearch方法得到的返回值是 -插入点-1 = f//据此获取位置int i = Arrays.binarySearch(arr, random);int index = -i-1;
//        System.out.println(index);//根据索引获取数据System.out.println("抽到的数据是: "+list.get(index).toString());//修改权重为2分之1;list.get(index).setWeight(list.get(index).getWeight()/2);//将数据写会文件中BufferedWriter bw =  new BufferedWriter(new FileWriter("javaseday30\\a.txt"));for (Student student : list) {bw.write(student.toString());bw.newLine();}bw.close();}
}

登录注册

练习一

public class Test1 {public static void main(String[] args) throws IOException {//链接BufferedReader br = new BufferedReader(new FileReader("javaseday30\\userinfo.txt"));//将数据读取到list集合中ArrayList<User> list = new ArrayList<>();String str;while ((str = br.readLine())!=null){//拆解字符串得到数据String[] split = str.split("&");String[] split1 = split[0].split("=");String[] split2 = split[1].split("=");User user = new User(split1[1],split2[1]);list.add(user);}Scanner sc = new Scanner(System.in);System.out.println("请输入用户名");String name = sc.next();System.out.println("请输入密码");String password = sc.next();boolean flag = true;//遍历集合判断是否正确for (User user : list) {if (user.getName().equals(name)){if (user.getPassword().equals(password)){System.out.println("登录成功");flag = false;}}}if (flag){System.out.println("账号和密码错误");}}
}
public class User {private String name;private String password;public User() {}public User(String name, String password) {this.name = name;this.password = password;}/*** 获取* @return name*/public String getName() {return name;}/*** 设置* @param name*/public void setName(String name) {this.name = name;}/*** 获取* @return password*/public String getPassword() {return password;}/*** 设置* @param password*/public void setPassword(String password) {this.password = password;}public String toString() {return "User{name = " + name + ", password = " + password + "}";}
}

 

练习二:

 

public class Test2 {public static void main(String[] args) throws IOException {//链接BufferedReader br = new BufferedReader(new FileReader("javaseday30\\userinfo.txt"));//将数据读取到list集合中HashSet<User> list = new HashSet<>();String str;while ((str = br.readLine())!=null){//拆解字符串得到数据String[] split = str.split("&");String[] split1 = split[0].split("=");String[] split2 = split[1].split("=");String[] split3 = split[2].split("=");int i = Integer.parseInt(split3[1]);User user = new User(split1[1],split2[1],i);list.add(user);}Scanner sc = new Scanner(System.in);System.out.println("请输入用户名");String name = sc.next();System.out.println("请输入密码");String password = sc.next();boolean flag = true;//遍历集合判断是否正确for (User user : list) {if (user.getName().equals(name)){//判断是否登录超过3次if (user.getCount()>=3){System.out.println("您已经连续输错三次密码,请与相关人员联系");flag = false;//修改登录次数int n = user.getCount()+1;user.setCount(n);//写入文件BufferedWriter bw = new BufferedWriter(new FileWriter("javaseday30\\userinfo.txt"));for (User user1 : list) {bw.write(user1.toString());bw.newLine();}bw.close();return;}if (user.getPassword().equals(password)){System.out.println("登录成功");flag = false;//登录成功则将登录次数置为0int n = 0;user.setCount(n);//写入文件BufferedWriter bw = new BufferedWriter(new FileWriter("javaseday30\\userinfo.txt"));for (User user1 : list) {bw.write(user1.toString());bw.newLine();}bw.close();}else {//修改登录次数int n = user.getCount()+1;user.setCount(n);//写入文件BufferedWriter bw = new BufferedWriter(new FileWriter("javaseday30\\userinfo.txt"));for (User user1 : list) {bw.write(user1.toString());bw.newLine();}bw.close();}}}if (flag){System.out.println("账号或密码错误");}}
}

修改了USer类,添加了登录次数和toString方法。

 

public class User {private String name;private String password;private int count;public User() {}public User(String name, String password, int count) {this.name = name;this.password = password;this.count = count;}/*** 获取* @return name*/public String getName() {return name;}/*** 设置* @param name*/public void setName(String name) {this.name = name;}/*** 获取* @return password*/public String getPassword() {return password;}/*** 设置* @param password*/public void setPassword(String password) {this.password = password;}/*** 获取* @return count*/public int getCount() {return count;}/*** 设置* @param count*/public void setCount(int count) {this.count = count;}public String toString() {return "username="+name+"&password="+password+"&count="+count;}
}

练习三:

 练习四:

练习三和练习四写在了一起 

package com.itheima.ui;import cn.hutool.core.io.FileUtil;
import com.itheima.domain.User;
import com.itheima.util.CodeUtil;import javax.swing.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.List;import static cn.hutool.core.map.MapUtil.getDate;public class LoginJFrame extends JFrame implements MouseListener {ArrayList<User> allUsers = new ArrayList<>();JButton login = new JButton();JButton register = new JButton();JTextField username = new JTextField();//JTextField password = new JTextField();JPasswordField password = new JPasswordField();JTextField code = new JTextField();//正确的验证码JLabel rightCode = new JLabel();public LoginJFrame() {//读取数据getDate();//初始化界面initJFrame();//在这个界面中添加内容initView();//让当前界面显示出来this.setVisible(true);}private void getDate() {//读取数据List<String> list = FileUtil.readUtf8Lines("C:\\Users\\20724\\Desktop\\demo\\javase2day01\\puzzlegame\\userinfo.txt");//处理数据for (String s : list) {String[] split = s.split("&");String[] split1 = split[0].split("=");String[] split2 = split[1].split("=");String[] split3 = split2[1].split("-");User u = new User(split1[1],split3[0],Integer.parseInt(split3[1]));allUsers.add(u);}}public void initView() {//1. 添加用户名文字JLabel usernameText = new JLabel(new ImageIcon("puzzlegame\\image\\login\\用户名.png"));usernameText.setBounds(116, 135, 47, 17);this.getContentPane().add(usernameText);//2.添加用户名输入框username.setBounds(195, 134, 200, 30);this.getContentPane().add(username);//3.添加密码文字JLabel passwordText = new JLabel(new ImageIcon("puzzlegame\\image\\login\\密码.png"));passwordText.setBounds(130, 195, 32, 16);this.getContentPane().add(passwordText);//4.密码输入框password.setBounds(195, 195, 200, 30);this.getContentPane().add(password);//验证码提示JLabel codeText = new JLabel(new ImageIcon("puzzlegame\\image\\login\\验证码.png"));codeText.setBounds(133, 256, 50, 30);this.getContentPane().add(codeText);//验证码的输入框code.setBounds(195, 256, 100, 30);code.addMouseListener(this);this.getContentPane().add(code);String codeStr = CodeUtil.getCode();//设置内容rightCode.setText(codeStr);//绑定鼠标事件rightCode.addMouseListener(this);//位置和宽高rightCode.setBounds(300, 256, 50, 30);//添加到界面this.getContentPane().add(rightCode);//5.添加登录按钮login.setBounds(123, 310, 128, 47);login.setIcon(new ImageIcon("puzzlegame\\image\\login\\登录按钮.png"));//去除按钮的边框login.setBorderPainted(false);//去除按钮的背景login.setContentAreaFilled(false);//给登录按钮绑定鼠标事件login.addMouseListener(this);this.getContentPane().add(login);//6.添加注册按钮register.setBounds(256, 310, 128, 47);register.setIcon(new ImageIcon("puzzlegame\\image\\login\\注册按钮.png"));//去除按钮的边框register.setBorderPainted(false);//去除按钮的背景register.setContentAreaFilled(false);//给注册按钮绑定鼠标事件register.addMouseListener(this);this.getContentPane().add(register);//7.添加背景图片JLabel background = new JLabel(new ImageIcon("puzzlegame\\image\\login\\background.png"));background.setBounds(0, 0, 470, 390);this.getContentPane().add(background);}public void initJFrame() {this.setSize(488, 430);//设置宽高this.setTitle("拼图游戏 V1.0登录");//设置标题this.setDefaultCloseOperation(3);//设置关闭模式this.setLocationRelativeTo(null);//居中this.setAlwaysOnTop(true);//置顶this.setLayout(null);//取消内部默认布局}//点击@Overridepublic void mouseClicked(MouseEvent e) {if (e.getSource() == login) {System.out.println("点击了登录按钮");//获取两个文本输入框中的内容String usernameInput = username.getText();String passwordInput = password.getText();//获取用户输入的验证码String codeInput = code.getText();//创建一个User对象User userInfo = new User(usernameInput, passwordInput,0);System.out.println("用户输入的用户名为" + usernameInput);System.out.println("用户输入的密码为" + passwordInput);if (codeInput.length() == 0) {showJDialog("验证码不能为空");} else if (usernameInput.length() == 0 || passwordInput.length() == 0) {//校验用户名和密码是否为空System.out.println("用户名或者密码为空");//调用showJDialog方法并展示弹框showJDialog("用户名或者密码为空");} else if (!codeInput.equalsIgnoreCase(rightCode.getText())) {showJDialog("验证码输入错误");} else if (contains(userInfo)) {System.out.println("用户名和密码正确可以开始玩游戏了");//关闭当前登录界面this.setVisible(false);//打开游戏的主界面//需要把当前登录的用户名传递给游戏界面new GameJFrame();} else {System.out.println("用户名或密码错误");showJDialog("用户名或密码错误");//更改登录错误的次数//遍历集合看有没相同的用户名for (User user : allUsers) {if (user.getUsername().equals(usernameInput)){user.setCount(user.getCount()+1);//将数据写回文件FileUtil.writeLines(allUsers,"C:\\Users\\20724\\Desktop\\demo\\javase2day01\\puzzlegame\\userinfo.txt","UTF-8");}}}} else if (e.getSource() == register) {System.out.println("点击了注册按钮");//关闭当前页面this.setVisible(false);//打开注册页面,并将数据传入new RegisterJFrame(allUsers);} else if (e.getSource() == rightCode) {System.out.println("更换验证码");//获取一个新的验证码String code = CodeUtil.getCode();rightCode.setText(code);}}public void showJDialog(String content) {//创建一个弹框对象JDialog jDialog = new JDialog();//给弹框设置大小jDialog.setSize(200, 150);//让弹框置顶jDialog.setAlwaysOnTop(true);//让弹框居中jDialog.setLocationRelativeTo(null);//弹框不关闭永远无法操作下面的界面jDialog.setModal(true);//创建Jlabel对象管理文字并添加到弹框当中JLabel warning = new JLabel(content);warning.setBounds(0, 0, 200, 150);jDialog.getContentPane().add(warning);//让弹框展示出来jDialog.setVisible(true);}//按下不松@Overridepublic void mousePressed(MouseEvent e) {if (e.getSource() == login) {login.setIcon(new ImageIcon("puzzlegame\\image\\login\\登录按下.png"));} else if (e.getSource() == register) {register.setIcon(new ImageIcon("puzzlegame\\image\\login\\注册按下.png"));}}//松开按钮@Overridepublic void mouseReleased(MouseEvent e) {if (e.getSource() == login) {login.setIcon(new ImageIcon("puzzlegame\\image\\login\\登录按钮.png"));} else if (e.getSource() == register) {register.setIcon(new ImageIcon("puzzlegame\\image\\login\\注册按钮.png"));}}//鼠标划入@Overridepublic void mouseEntered(MouseEvent e) {}//鼠标划出@Overridepublic void mouseExited(MouseEvent e) {}//判断用户在集合中是否存在public boolean contains(User userInput){for (int i = 0; i < allUsers.size(); i++) {User rightUser = allUsers.get(i);//先判断重复错误登录的次数if (userInput.getUsername().equals(rightUser.getUsername())){int count = rightUser.getCount();if (count>=3){showJDialog("您密码错误的次数已经超过三次,账号被锁定,请联系相关人员处理");return false;}}if(userInput.getUsername().equals(rightUser.getUsername()) && userInput.getPassword().equals(rightUser.getPassword())){//有相同的代表存在,返回true,后面的不需要再比了rightUser.setCount(0);//将数据写回文件FileUtil.writeLines(allUsers,"C:\\Users\\20724\\Desktop\\demo\\javase2day01\\puzzlegame\\userinfo.txt","UTF-8");return true;}}//循环结束之后还没有找到就表示不存在return false;}}
package com.itheima.ui;import cn.hutool.core.io.FileUtil;
import com.itheima.domain.User;import javax.swing.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;public class RegisterJFrame extends JFrame implements MouseListener {//存储已经注册的用户信息,赋值为null等待写入数据ArrayList<User> allUsers = null;//提升三个输入框的变量的作用范围,让这三个变量可以在本类中所有方法里面可以使用。JTextField username = new JTextField();JTextField password = new JTextField();JTextField rePassword = new JTextField();//提升两个按钮变量的作用范围,让这两个变量可以在本类中所有方法里面可以使用。JButton submit = new JButton();JButton reset = new JButton();public RegisterJFrame(ArrayList<User> allUsers) {this.allUsers = allUsers;initFrame();initView();setVisible(true);}//点击判断@Overridepublic void mouseClicked(MouseEvent e) {if (e.getSource() == submit) {//点击注册按钮//判断三个数据是否为空String usernameText = username.getText();String passwordText = password.getText();String rePasswordText = rePassword.getText();if (usernameText.length()==0){showDialog("用户为空,请重新输入");return;}if (passwordText.length()==0){showDialog("密码为空,请重新输入");return;}if (rePasswordText.length()==0){showDialog("确认密码为空,请重新输入");return;}//判断两个密码是否一致if (!passwordText.equals(rePasswordText)){showDialog("两次密码输入不相同,请重新输入");return;}//判断用户名密码是否符合要求if (!usernameText.matches("[a-zA-Z0-9_-]{4,16}")){showDialog("用户名不符合要求,请重新输入");return;}if (!passwordText.matches("\\S*(?=\\S{6,})(?=\\S*\\d)(?=\\S*[A-Z])\\S*")){showDialog("密码不符合要求,至少包含1个小写字母,1个数字长度至少6位,请重新输入");return;}//判断用户名是否重复for (User user : allUsers) {if (user.getUsername().equals(usernameText)){showDialog("用户名已存在,请重新输入");return;}}//写入数据User user = new User(usernameText,passwordText,0);allUsers.add(user);FileUtil.writeLines(allUsers,"C:\\Users\\20724\\Desktop\\demo\\javase2day01\\puzzlegame\\userinfo.txt","UTF-8");//表示用户注册成功showDialog("恭喜注册成功");//关闭当前页面this.setVisible(false);//打开登录页面new LoginJFrame();} else if (e.getSource() == reset) {//点击重置按钮,将三个输入框赋值为“”//点击重置按钮,将三个输入框赋值为“”username.setText("");password.setText("");rePassword.setText("");}}@Overridepublic void mousePressed(MouseEvent e) {if (e.getSource() == submit) {submit.setIcon(new ImageIcon("puzzlegame\\image\\register\\注册按下.png"));} else if (e.getSource() == reset) {reset.setIcon(new ImageIcon("puzzlegame\\image\\register\\重置按下.png"));}}@Overridepublic void mouseReleased(MouseEvent e) {if (e.getSource() == submit) {submit.setIcon(new ImageIcon("puzzlegame\\image\\register\\注册按钮.png"));} else if (e.getSource() == reset) {reset.setIcon(new ImageIcon("puzzlegame\\image\\register\\重置按钮.png"));}}@Overridepublic void mouseEntered(MouseEvent e) {}@Overridepublic void mouseExited(MouseEvent e) {}private void initView() {//添加注册用户名的文本JLabel usernameText = new JLabel(new ImageIcon("puzzlegame\\image\\register\\注册用户名.png"));usernameText.setBounds(85, 135, 80, 20);//添加注册用户名的输入框username.setBounds(195, 134, 200, 30);//添加注册密码的文本JLabel passwordText = new JLabel(new ImageIcon("puzzlegame\\image\\register\\注册密码.png"));passwordText.setBounds(97, 193, 70, 20);//添加密码输入框password.setBounds(195, 195, 200, 30);//添加再次输入密码的文本JLabel rePasswordText = new JLabel(new ImageIcon("puzzlegame\\image\\register\\再次输入密码.png"));rePasswordText.setBounds(64, 255, 95, 20);//添加再次输入密码的输入框rePassword.setBounds(195, 255, 200, 30);//注册的按钮submit.setIcon(new ImageIcon("puzzlegame\\image\\register\\注册按钮.png"));submit.setBounds(123, 310, 128, 47);submit.setBorderPainted(false);submit.setContentAreaFilled(false);submit.addMouseListener(this);//重置的按钮reset.setIcon(new ImageIcon("puzzlegame\\image\\register\\重置按钮.png"));reset.setBounds(256, 310, 128, 47);reset.setBorderPainted(false);reset.setContentAreaFilled(false);reset.addMouseListener(this);//背景图片JLabel background = new JLabel(new ImageIcon("puzzlegame\\image\\register\\background.png"));background.setBounds(0, 0, 470, 390);this.getContentPane().add(usernameText);this.getContentPane().add(passwordText);this.getContentPane().add(rePasswordText);this.getContentPane().add(username);this.getContentPane().add(password);this.getContentPane().add(rePassword);this.getContentPane().add(submit);this.getContentPane().add(reset);this.getContentPane().add(background);}private void initFrame() {//对自己的界面做一些设置。//设置宽高setSize(488, 430);//设置标题setTitle("拼图游戏 V1.0注册");//取消内部默认布局setLayout(null);//设置关闭模式setDefaultCloseOperation(3);//设置居中setLocationRelativeTo(null);//设置置顶setAlwaysOnTop(true);}//只创建一个弹框对象JDialog jDialog = new JDialog();//因为展示弹框的代码,会被运行多次//所以,我们把展示弹框的代码,抽取到一个方法中。以后用到的时候,就不需要写了//直接调用就可以了。public void showDialog(String content){if(!jDialog.isVisible()){//把弹框中原来的文字给清空掉。jDialog.getContentPane().removeAll();JLabel jLabel = new JLabel(content);jLabel.setBounds(0,0,200,150);jDialog.add(jLabel);//给弹框设置大小jDialog.setSize(200, 150);//要把弹框在设置为顶层 -- 置顶效果jDialog.setAlwaysOnTop(true);//要让jDialog居中jDialog.setLocationRelativeTo(null);//让弹框jDialog.setModal(true);//让jDialog显示出来jDialog.setVisible(true);}}
}
package com.itheima.domain;public class User {private String username;private String password;private int count;@Overridepublic String toString() {return "username="+username+"&password="+password+"-"+count;}public User() {}public User(String username, String password,int count) {this.username = username;this.password = password;this.count = count;}/*** 获取* @return username*/public String getUsername() {return username;}/*** 设置* @param username*/public void setUsername(String username) {this.username = username;}/*** 获取* @return password*/public String getPassword() {return password;}/*** 设置* @param password*/public void setPassword(String password) {this.password = password;}public int getCount() {return count;}public void setCount(int count) {this.count = count;}
}

游戏的存档和读档

游戏配置

public class Demo1 {public static void main(String[] args) {//创建集合对象Properties properties = new Properties();//Properties是一个Map集合,可以使用Map集合的方法,通常只存入字符串properties.put(1,2);properties.put(2,3);properties.put(4,2);properties.put(5,2);properties.put(6,2);//Properties的独特方法//Map集合的方法
//        Set<Map.Entry<Object, Object>> entries = properties.entrySet();
//        for (Map.Entry<Object, Object> entry : entries) {
//            System.out.println(entry.getKey()+"="+entry.getValue());
//        }
//        Set<Object> objects = properties.keySet();
//        for (Object object : objects) {
//            System.out.println(object+"="+properties.get(object));
//        }}
}
public class Demo2 {public static void main(String[] args) throws IOException {//Properties和IO流结合//        //创建集合对象Properties properties = new Properties();//Properties是一个Map集合,可以使用Map集合的方法,通常只存入字符串properties.put("asd","dsdsd");properties.put("mnkev","dsdsd");BufferedWriter fos = new BufferedWriter(new FileWriter("C:\\Users\\20724\\Desktop\\demo\\javase2day01\\javaseday30\\a.properties"));//参数二:对文件的注解properties.store(fos,"test");fos.close();//普通的流操作
//        BufferedWriter fos = new BufferedWriter(new FileWriter("C:\\Users\\20724\\Desktop\\demo\\javase2day01\\javaseday30\\a.properties"));
//        String str;
//        Set<Object> objects = properties.keySet();
//        for (Object object : objects) {
//            Object value = properties.get(object);
//            fos.write(object+"="+value);
//            fos.newLine();
//        }
//        fos.close();}
}
public class Demo3 {public static void main(String[] args) throws IOException {//从文件中读取数据Properties properties = new Properties();FileInputStream fis = new FileInputStream("C:\\Users\\20724\\Desktop\\demo\\javase2day01\\javaseday30\\a.properties");properties.load(fis);fis.close();System.out.println(properties.toString());}
}

配置公众号显示的图片

        } else if (obj == accountItem) {System.out.println("公众号");//创建一个弹框对象JDialog jDialog = new JDialog();//创建键一个配置文件对象Properties properties = new Properties();try {//创建一个流读取配置文件FileInputStream fis= new FileInputStream("puzzlegame\\game.properties");//读取数据properties.load(fis);fis.close();} catch (IOException ex) {throw new RuntimeException(ex);}String path = (String) properties.get("acount");//创建一个管理图片的容器对象JLabelJLabel jLabel = new JLabel(new ImageIcon(path));//设置位置和宽高jLabel.setBounds(0, 0, 258, 258);//把图片添加到弹框当中jDialog.getContentPane().add(jLabel);//给弹框设置大小jDialog.setSize(344, 344);//让弹框置顶jDialog.setAlwaysOnTop(true);//让弹框居中jDialog.setLocationRelativeTo(null);//弹框不关闭则无法操作下面的界面jDialog.setModal(true);//让弹框显示出来jDialog.setVisible(true);


http://www.ppmy.cn/devtools/115708.html

相关文章

读取t x t文件生成exce

读取t x t文件生成excel package com.moka.api.custom.core.controller; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermode…

c语言中define使用方法

在C语言中&#xff0c;#define指令是预处理指令&#xff0c;用于定义宏。其常用格式是&#xff1a; 定义常量&#xff1a; #define 常量名 常量值 例子&#xff1a; #define PI 3.14159 #define MAX_SIZE 100 这里&#xff0c;PI和MAX_SIZE在代码中会被替换为其对应的值。没有…

音视频入门基础:AAC专题(8)——FFmpeg源码中计算AAC裸流AVStream的time_base的实现

音视频入门基础&#xff1a;AAC专题系列文章&#xff1a; 音视频入门基础&#xff1a;AAC专题&#xff08;1&#xff09;——AAC官方文档下载 音视频入门基础&#xff1a;AAC专题&#xff08;2&#xff09;——使用FFmpeg命令生成AAC裸流文件 音视频入门基础&#xff1a;AAC…

如何制作ubuntu启动U盘

步骤&#xff1a; 选择一个U盘&#xff0c;千万不要超过32G&#xff08;因fat32不支持超过32G的卷&#xff09;下载ubuntu镜像&#xff0c;我选择的是优麒麟的20.04&#xff0c;主要因为大小适中使用rufus工具将ubuntu镜像写入U盘在新电脑上插入U盘&#xff0c;进bios设置USB启…

ubuntu安装wordpress(基于LNMP环境)

参考链接 Ubuntu安装LNMP 安装步骤 环境需要LNMP环境&#xff0c;如果没有安装可以参考ZATA—LNMP简单安装 在mysql中设置wordpress所用的用户名和密码 #1. 登录mysql mysql -uroot -p #2. 创建wordpress数据库 create database wordpress; #3. 创建新用户user&#xff0c;…

【Taro】初识 Taro

笔记来源&#xff1a;编程导航。 概述 Taro 官方文档&#xff1a;https://taro-docs.jd.com/docs/ &#xff08;跨端开发框架&#xff09; Taro 官方框架兼容的组件库&#xff1a; taro-ui&#xff1a;https://taro-ui.jd.com/#/ &#xff08;最推荐&#xff0c;兼容性最好&…

C++标准库容器类——string类

引言 在c中&#xff0c;string类的引用极大地简化了字符串的操作和管理&#xff0c;相比 C 风格字符串&#xff08;char*或cahr[]&#xff09;&#xff0c;std::string 提供了更高效和更安全的字符串操作。接下来让我们一起来深入学习string类吧&#xff01; 1.string 的构造…

❤Node09-用户信息token认证

❤Node09-用户信息token认证​ 1、安装​ jsonwebtoken 比较官方的称呼为JSON Web Token&#xff08;JWT&#xff09;,一种开放标准&#xff08;RFC 7519&#xff09;,就类似砸门认知的w3c&#xff0c;主要就是更安全地传输信息。利用数字签名验证数据的完整性和身份。 所以J…