This commit is contained in:
2025-12-21 17:24:54 +08:00
commit e8c50a3d78
660 changed files with 29599 additions and 0 deletions

8
day01/books-schema.xml Normal file
View File

@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8" ?>
<books xmlns="books1.xsd">
<book address="dd">
<name></name>
<autor></autor>
<price></price>
</book>
</books>

6
day01/books.dtd Normal file
View File

@@ -0,0 +1,6 @@
<!ELEMENT books (book+)>
<!ELEMENT book (name,price,author)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT price (#PCDATA)>
<!ELEMENT author (#PCDATA)>
<!ATTLIST book bid CDATA "check">

25
day01/books.xml Normal file
View File

@@ -0,0 +1,25 @@
<?xml version="1.0" encoding="utf-8" ?>
<!--dtd约束文件的内部引入-->
<!--<!DOCTYPE books [
<!ELEMENT books (book+)>
<!ELEMENT book (name,price,author)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT price (#PCDATA)>
<!ELEMENT author (#PCDATA)>
<!ATTLIST book bid CDATA "check">
]>-->
<!--dtd约束文件的外部引入-->
<!DOCTYPE books SYSTEM "books.dtd">
<books>
<book bid="j">
<name>java入门到精通</name>
<price>999</price>
<author>小王</author>
</book>
<book bid="s">
<name>数据库从删库到跑路</name>
<price>666</price>
<author>老王</author>
</book>
</books>

26
day01/books1.xsd Normal file
View File

@@ -0,0 +1,26 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
schema约束文件的根标签必须是schema
目标命名空间:类似java中的包名,用来在执行的xml中来导入约束文件
targetNamespace="http://www.example.org/books"
-->
<schema xmlns="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.emample.org/books"
elementFormDefault="qualified">
<element name="books">
<complexType>
<sequence>
<element name="book" maxOccurs="unbounded">
<complexType>
<sequence>
<element name="name" type="string"></element>
<element name="autor" type="string"></element>
<element name="price" type="string"></element>
</sequence>
<attribute name="address"></attribute>
</complexType>
</element>
</sequence>
</complexType>
</element>
</schema>

View File

@@ -0,0 +1,4 @@
package com.inmind;
public class ChildClass {
}

View File

@@ -0,0 +1,92 @@
package com.inmind;
public class Demo01 {
public static void main(String[] args) {
// 假设 player1 和 player2 已经初始化
Player player1 = new Player("y", "qfz", 22, new Weapon("AK47", 36, 28));
Player player2 = new Player("s", "bwz", 16, new Weapon("M4A1", 36, 28));
// 打印对战结果
System.out.println("\n===== 第8回合 =====");
System.out.println("潜伏者 影 使用 AK47 向保卫者 隼 开火!");
System.out.println("AK47剩余弹药: (28/36)");
System.out.println("未命中");
System.out.println("保卫者 隼 使用 M4A1 向潜伏者 影 开火!");
System.out.println("M4A1剩余弹药: (28/36)");
System.out.println("保卫者 隼 使用 M4A1 对潜伏者 影 造成了 39 点伤害");
player1.setCurrentHealth(player1.getCurrentHealth() - 39);
System.out.println("潜伏者 影受到 39 点伤害 剩余血量为: " + player1.getCurrentHealth());
// 显示当前状态
System.out.println("\n【当前状态】");
System.out.printf("| %-8s | %-8s | %-9s |\n", "player-X", "smz", "dqwq");
System.out.printf("| %-8s | %-8d | %-9s |\n",
player1.getFaction() + "-" + player1.getName(),
player1.getCurrentHealth(),
player1.getCurrentWeapon().getName());
System.out.printf("| %-8s | %-8d | %-9s |\n",
player2.getFaction() + "-" + player2.getName(),
player2.getCurrentHealth(),
player2.getCurrentWeapon().getName());
// 战斗结果
System.out.println("\n===== 战斗结束! =====");
Player winner = player1.isEliminated() ? player2 : player1;
System.out.println("胜者: " + winner.getFaction() + "-" + winner.getName());
}
}
class Player {
private String name;
private String faction;
private int currentHealth;
private Weapon currentWeapon;
public Player(String name, String faction, int currentHealth, Weapon currentWeapon) {
this.name = name;
this.faction = faction;
this.currentHealth = currentHealth;
this.currentWeapon = currentWeapon;
}
public String getName() {
return name;
}
public String getFaction() {
return faction;
}
public int getCurrentHealth() {
return currentHealth;
}
public void setCurrentHealth(int currentHealth) {
this.currentHealth = currentHealth;
}
public Weapon getCurrentWeapon() {
return currentWeapon;
}
public boolean isEliminated() {
return currentHealth <= 0;
}
}
class Weapon {
private String name;
private int maxAmmo;
private int currentAmmo;
public Weapon(String name, int maxAmmo, int currentAmmo) {
this.name = name;
this.maxAmmo = maxAmmo;
this.currentAmmo = currentAmmo;
}
public String getName() {
return name;
}
}

View File

@@ -0,0 +1,25 @@
package com.inmind;
public class Demo02 {
public static void main(String[] args) {
/* String a = "abc";
String b = "ab";
String c = "";
for (int i = 0; i < 1000000; i++) {
c+=a+b;
}
System.out.println(c);*/
method();
}
public static void method() {
String a = "abc";
String b = "ab";
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 1000000; i++) {
sb.append(a).append(b);
}
System.out.println(sb);
}
}

View File

@@ -0,0 +1,45 @@
package com.inmind;
/*
方法的定义格式
修饰符 返回值类型 方法名(参数列表){
方法体;
}
a. 修饰符 public static (固定)
b. 返回值类型:
没有返回值void
有返回值基本数据类型4类型八种
c.方法名:标识符(硬性要求,软性建议小驼峰)
d.():参数列表
如果没有参数()
如果有参数,直接在()定义
2个int参数(int a,int b)
e.方法体java代码的集合
在方法中可以使用关键return就是结束当前方法并且如果有返回值直接在
return之后 编写。将return后的值返回到方法调用处。
方法定义的2个明确
1.明确返回值类型
2.明确参数列表
案例定义一个方法实现2个整数值的相加操作并将和值返回
*/
public class DemoMethod {
public static void main(String[] args) {
MyInterfaceImpl myInterface = new MyInterfaceImpl();
myInterface.method();
myInterface.method2();
}
/**
*
* @param a
* @param b
* @return
*/
public static int getSum(int a,int b){
int sum = a+b;
return sum;
}
}

View File

@@ -0,0 +1,4 @@
package com.inmind;
public final class FinalClass {
}

View File

@@ -0,0 +1,24 @@
package com.inmind;
public class ForTest {
public static void main(String[] args) {
printJiuJiu();
}
public static void printJiuJiu() {
/*
方法_回顾_打印九九乘法表
11
12 22
13 23 33
14 24 34 44
*/
for (int i = 1; i < 10; i++) {
// System.out.println(i);
for (int j = 1; j <= i ; j++) {
System.out.print(j+"*"+i+"="+(i*j)+" ");
}
System.out.println();
}
}
}

View File

@@ -0,0 +1,20 @@
package com.inmind;
import java.util.Scanner;
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World");
if (2 > 1) {
}
int a = 1;
int b = 2;
int c = 3;
}
}

View File

@@ -0,0 +1,9 @@
package com.inmind;
public interface MyInterfaceDefault {
public static final int i = 10;
void method();
default void method2() {
System.out.println("method2");
}
}

View File

@@ -0,0 +1,14 @@
package com.inmind;
public class MyInterfaceImpl implements MyInterfaceDefault{
@Override
public void method() {
}
@Override
public void method2() {
MyInterfaceDefault.super.method2();
System.out.println("实现类的method2方法");
}
}

View File

@@ -0,0 +1,27 @@
package com.inmind;
import java.util.Date;
import java.util.StringJoiner;
public class SystemDemo {
public static void main(String[] args) {
// 获取 Java 版本
String javaVersion = System.getProperty("java.version");
// 获取操作系统名称
String osName = System.getProperty("os.name");
// 获取环境变量 PATH
String path = System.getenv("PATH");
String ossID = System.getenv("OSS_ACCESS_KEY_ID");
System.out.println(javaVersion);
System.out.println(osName);
System.out.println(path);
System.out.println(ossID);
new Date();
new StringJoiner(",");
System.out.println(System.currentTimeMillis());
}
}

View File

@@ -0,0 +1,86 @@
package com.inmind;
import java.util.TreeSet;
import java.util.Comparator;
import java.util.Iterator;
public class TreeSetDemo {
public static void main(String[] args) {
// 1. 创建 TreeSet默认自然排序
TreeSet<Integer> set1 = new TreeSet<>();
// 2. 创建 TreeSet指定比较器如降序排序
TreeSet<Integer> set2 = new TreeSet<>(Comparator.reverseOrder());
// 3. 添加元素add()
set1.add(3);
set1.add(1);
set1.add(2);
set1.add(2); // 重复元素,添加失败
System.out.println(set1); // 输出:[1, 2, 3](自动排序)
// 4. 删除元素remove()
set1.remove(2);
System.out.println(set1); // 输出:[1, 3]
// 5. 判断元素是否存在contains()
boolean has3 = set1.contains(3);
System.out.println(has3); // 输出true
// 6. 获取集合大小size()
int size = set1.size();
System.out.println(size); // 输出2
// 7. 清空集合clear()
// set1.clear();
// 8. 迭代元素(升序)
System.out.print("升序迭代:");
for (Integer num : set1) {
System.out.print(num + " ");
}
// 9. 降序迭代descendingIterator()
System.out.print("\n降序迭代");
Iterator<Integer> it = set1.descendingIterator();
while (it.hasNext()) {
System.out.print(it.next() + " ");
}
// 10. 获取第一个元素first()
Integer first = set1.first();
System.out.println("\n第一个元素" + first); // 输出1
// 11. 获取最后一个元素last()
Integer last = set1.last();
System.out.println("最后一个元素:" + last); // 输出3
// 12. 获取小于指定元素的最大元素lower()
Integer lower = set1.lower(3);
System.out.println("小于3的最大元素" + lower); // 输出1
// 13. 获取小于等于指定元素的最大元素floor()
Integer floor = set1.floor(3);
System.out.println("小于等于3的最大元素" + floor); // 输出3
// 14. 获取大于指定元素的最小元素higher()
Integer higher = set1.higher(1);
System.out.println("大于1的最小元素" + higher); // 输出3
// 15. 获取大于等于指定元素的最小元素ceiling()
Integer ceiling = set1.ceiling(1);
System.out.println("大于等于1的最小元素" + ceiling); // 输出1
// 16. 截取子集合headSet():小于指定元素)
TreeSet<Integer> headSet = (TreeSet<Integer>) set1.headSet(3);
System.out.println("小于3的子集合" + headSet); // 输出:[1]
// 17. 截取子集合tailSet():大于等于指定元素)
TreeSet<Integer> tailSet = (TreeSet<Integer>) set1.tailSet(1);
System.out.println("大于等于1的子集合" + tailSet); // 输出:[1, 3]
// 18. 截取子集合subSet()大于等于fromElement小于toElement
TreeSet<Integer> subSet = (TreeSet<Integer>) set1.subSet(1, 3);
System.out.println("子集合[1,3)" + subSet); // 输出:[1]
}
}

View File

@@ -0,0 +1,42 @@
package com.inmind;
import com.inmind.test07.Student;
import java.util.Comparator;
import java.util.Iterator;
import java.util.TreeMap;
import java.util.TreeSet;
public class TreeSetDemo1 {
public static void main(String[] args) {
TreeSet<Student> treeSet = new TreeSet<>(new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
return o2.getId() - o1.getId();
}
});
Student s1 = new Student();
s1.setId(1);
Student s2 = new Student();
s2.setId(3);
Student s3 = new Student();
s3.setId(5);
treeSet.add(s1);
treeSet.add(s2);
treeSet.add(s3);
System.out.println(treeSet);
TreeMap<Student, String> treeMap = new TreeMap<>(new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
return o2.getId() - o1.getId();
}
});
treeMap.put(s1, "<UNK>");
treeMap.put(s2, "<UNK>");
treeMap.put(s3, "<UNK>");
System.out.println(treeMap);
}
}

View File

@@ -0,0 +1,33 @@
package com.inmind.logback;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class LogBackTest {
//创建一个logger日志对象
public static final Logger LOGGER = LoggerFactory.getLogger("LogBackTest");
public static void main(String[] args) {
while (true) {
try{
LOGGER.info("chiufa方法开始执行了~~~~");
chufa(10,0);
LOGGER.info("chiufa方法执行成功了~~~~");
}catch (Exception e){
LOGGER.error("chiufa方法执行失败了出现了异常~~~~");
// e.printStackTrace();
}
}
}
public static void chufa(int a,int b) {
//记录程序方法的执行流程
LOGGER.debug("参数a:"+a);
LOGGER.debug("参数b:"+b);
int c = a/b;
//System.out.println("结果是:"+c);(下面使用了LOGGER这里就不用sout了)
//结果比较重要使用info
LOGGER.info("结果是:"+c);
}
}

View File

@@ -0,0 +1,131 @@
package com.inmind.s_test055;
// 1. 支付失败异常类继承自Exception受检异常
class PaymentFailedException extends Exception {
// 业务字段:存储异常相关的订单号,用于后续问题定位
private String orderId;
// 业务字段:存储异常涉及的支付金额,方便业务分析
private double amount;
// 业务字段存储业务系统内部定义的错误码如PAY001、PAY002
private String errorCode;
// 构造方法:初始化异常信息和业务上下文数据
// 参数说明:
// message异常的描述信息
// orderId关联的订单编号
// amount涉及的支付金额
// errorCode业务错误编码
public PaymentFailedException(String message, String orderId,
double amount, String errorCode) {
super(message); // 调用父类Exception的构造方法传递异常描述
this.orderId = orderId; // 初始化订单号字段
this.amount = amount; // 初始化支付金额字段
this.errorCode = errorCode;// 初始化错误码字段
}
// 获取订单号的getter方法供上层代码获取异常关联的订单信息
public String getOrderId() {
return orderId;
}
// 获取支付金额的getter方法供上层代码获取异常涉及的金额
public double getAmount() {
return amount;
}
// 获取业务错误码的getter方法供上层代码根据错误码执行不同逻辑
public String getErrorCode() {
return errorCode;
}
// 生成面向业务的异常消息,整合所有上下文信息
// 格式化为适合业务人员理解的字符串
public String getBusinessMessage() {
// 使用String.format拼接包含订单号、金额、错误码和原因的完整消息
return String.format("订单[%s]支付失败(金额:%.2f),错误码:%s原因:%s",
orderId, amount, errorCode, getMessage());
}
// 记录业务异常日志的方法,统一异常日志格式
public void logToBusinessSystem() {
// 实际项目中会使用日志框架如Logback此处简化为控制台输出
// 输出包含业务标识的日志,便于后续排查问题
System.out.println("[业务日志] " + getBusinessMessage());
}
}
// 2. 订单不存在异常类继承自Exception
class OrderNotFoundException extends Exception {
// 业务字段:存储不存在的订单号
private String orderId;
// 构造方法:接收异常消息和订单号
public OrderNotFoundException(String message, String orderId) {
super(message); // 调用父类构造方法
this.orderId = orderId; // 初始化订单号字段
}
// 获取订单号的getter方法
public String getOrderId() {
return orderId;
}
// 生成业务友好的异常描述
public String getBusinessInfo() {
return "订单查询异常:订单号[" + orderId + "]不存在," + getMessage();
}
}
// 异常使用示例类
public class ExceptionDemo {
// 主方法:测试异常的抛出和处理
public static void main(String[] args) {
try {
// 调用支付处理方法,可能抛出自定义异常
processPayment("ORDER123456", 500.0);
}
// 捕获支付失败异常
catch (PaymentFailedException e) {
// 1. 获取业务消息并展示给用户
System.out.println("用户提示:" + e.getBusinessMessage());
// 2. 记录业务日志
e.logToBusinessSystem();
// 3. 根据错误码执行不同的补救逻辑
if ("PAY001".equals(e.getErrorCode())) {
System.out.println("系统处理:执行余额不足的补救流程...");
}
}
// 捕获订单不存在异常
catch (OrderNotFoundException e) {
System.out.println("处理异常:" + e.getBusinessInfo());
}
// 捕获其他未预料的异常
catch (Exception e) {
System.out.println("发生未知错误:" + e.getMessage());
}
}
// 模拟支付处理方法
private static void processPayment(String orderId, double amount)
throws PaymentFailedException, OrderNotFoundException {
// 模拟检查订单是否存在
if (!isOrderExists(orderId)) {
// 订单不存在时抛出对应的异常
throw new OrderNotFoundException("数据库中未查询到该订单", orderId);
}
// 模拟支付处理逻辑,此处假设支付失败
boolean paymentSuccess = false;
if (!paymentSuccess) {
// 支付失败时抛出自定义异常,携带完整业务上下文
throw new PaymentFailedException("账户余额不足",
orderId, amount, "PAY001");
}
}
// 模拟检查订单是否存在的方法
private static boolean isOrderExists(String orderId) {
// 此处简化逻辑假设ORDER123是不存在的订单
return !"ORDER123".equals(orderId);
}
}

View File

@@ -0,0 +1,483 @@
package com.inmind.s_test08;
import java.io.File;
import java.io.FilenameFilter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Scanner;
import java.util.stream.Collectors;
public class FileManager {
private static Scanner scanner = new Scanner(System.in);
private static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
private static String currentPath;
public static void main(String[] args) {
// 初始化当前路径为用户主目录
currentPath = System.getProperty("user.home");
showMainMenu();
}
// 显示主菜单
private static void showMainMenu() {
while (true) {
System.out.println("\n===== 文件管理工具 =====");
System.out.println("当前路径: " + currentPath);
System.out.println("1. 浏览当前目录");
System.out.println("2. 切换目录");
System.out.println("3. 创建新文件");
System.out.println("4. 创建新目录");
System.out.println("5. 删除文件/目录");
System.out.println("6. 搜索文件");
System.out.println("7. 文件统计信息");
System.out.println("8. 批量操作");
System.out.println("9. 退出");
System.out.print("请选择操作: ");
int choice;
try {
choice = Integer.parseInt(scanner.nextLine());
if (choice < 1 || choice > 9) {
System.out.println("请输入1-9之间的数字!");
continue;
}
} catch (NumberFormatException e) {
System.out.println("请输入有效的数字!");
continue;
}
switch (choice) {
case 1:
browseCurrentDirectory();
break;
case 2:
changeDirectory();
break;
case 3:
createNewFile();
break;
case 4:
createNewDirectory();
break;
case 5:
deleteFileOrDirectory();
break;
case 6:
searchFiles();
break;
case 7:
showFileStatistics();
break;
case 8:
batchOperations();
break;
case 9:
System.out.println("谢谢使用,再见!");
scanner.close();
return;
}
}
}
// 浏览当前目录
private static void browseCurrentDirectory() {
File currentDir = new File(currentPath);
if (!currentDir.exists() || !currentDir.isDirectory()) {
System.out.println("当前目录不存在或不是一个有效的目录!");
return;
}
System.out.println("\n===== 浏览目录: " + currentPath + " =====");
System.out.println("目录项列表:");
System.out.println("------------------------------------------------");
System.out.printf("%-4s %-40s %-12s %-20s%n", "类型", "名称", "大小", "修改时间");
System.out.println("------------------------------------------------");
File[] files = currentDir.listFiles();
if (files == null || files.length == 0) {
System.out.println("当前目录为空");
return;
}
// 先显示目录,再显示文件
for (File file : files) {
if (file.isDirectory()) {
printFileInfo(file);
}
}
for (File file : files) {
if (file.isFile()) {
printFileInfo(file);
}
}
System.out.println("------------------------------------------------");
System.out.println("" + files.length + " 个项目");
}
// 打印文件信息
private static void printFileInfo(File file) {
String type = file.isDirectory() ? "目录" : "文件";
String name = file.getName();
String size = file.isDirectory() ? "-" : (file.length() + " bytes");
String modifyTime = dateFormat.format(new Date(file.lastModified()));
System.out.printf("%-4s %-40s %-12s %-20s%n", type, name, size, modifyTime);
}
// 切换目录
private static void changeDirectory() {
System.out.println("\n===== 切换目录 =====");
System.out.print("请输入目标目录路径(输入..返回上一级): ");
String targetPath = scanner.nextLine().trim();
File newDir;
if (targetPath.equals("..")) {
// 返回上一级目录
newDir = new File(currentPath).getParentFile();
} else {
// 处理绝对路径和相对路径
if (new File(targetPath).isAbsolute()) {
newDir = new File(targetPath);
} else {
newDir = new File(currentPath + File.separator + targetPath);
}
}
if (newDir != null && newDir.exists() && newDir.isDirectory()) {
currentPath = newDir.getAbsolutePath();
System.out.println("已切换到目录: " + currentPath);
} else {
System.out.println("目录不存在或不是一个有效的目录!");
}
}
// 创建新文件
private static void createNewFile() {
System.out.println("\n===== 创建新文件 =====");
System.out.print("请输入新文件名称: ");
String fileName = scanner.nextLine().trim();
if (fileName.isEmpty()) {
System.out.println("文件名不能为空!");
return;
}
File newFile = new File(currentPath + File.separator + fileName);
if (newFile.exists()) {
System.out.println("文件已存在!");
return;
}
try {
boolean created = newFile.createNewFile();
if (created) {
System.out.println("文件创建成功: " + newFile.getAbsolutePath());
} else {
System.out.println("文件创建失败!");
}
} catch (Exception e) {
System.out.println("创建文件时发生错误: " + e.getMessage());
}
}
// 创建新目录
private static void createNewDirectory() {
System.out.println("\n===== 创建新目录 =====");
System.out.print("请输入新目录名称: ");
String dirName = scanner.nextLine().trim();
if (dirName.isEmpty()) {
System.out.println("目录名不能为空!");
return;
}
File newDir = new File(currentPath + File.separator + dirName);
if (newDir.exists()) {
System.out.println("目录已存在!");
return;
}
boolean created = newDir.mkdirs();
if (created) {
System.out.println("目录创建成功: " + newDir.getAbsolutePath());
} else {
System.out.println("目录创建失败!");
}
}
// 删除文件或目录
private static void deleteFileOrDirectory() {
System.out.println("\n===== 删除文件/目录 =====");
System.out.print("请输入要删除的文件/目录名称: ");
String name = scanner.nextLine().trim();
if (name.isEmpty()) {
System.out.println("名称不能为空!");
return;
}
File target = new File(currentPath + File.separator + name);
if (!target.exists()) {
System.out.println("文件/目录不存在!");
return;
}
System.out.print("确定要删除 " + name + " 吗? (y/n): ");
String confirm = scanner.nextLine().trim().toLowerCase();
if (!confirm.equals("y")) {
System.out.println("已取消删除操作");
return;
}
boolean deleted = deleteRecursively(target);
if (deleted) {
System.out.println("删除成功!");
} else {
System.out.println("删除失败!");
}
}
// 递归删除目录
private static boolean deleteRecursively(File file) {
if (file.isDirectory()) {
File[] children = file.listFiles();
if (children != null) {
for (File child : children) {
boolean success = deleteRecursively(child);
if (!success) {
return false;
}
}
}
}
return file.delete();
}
// 搜索文件
private static void searchFiles() {
System.out.println("\n===== 搜索文件 =====");
System.out.print("请输入搜索关键词: ");
String keyword = scanner.nextLine().trim().toLowerCase();
System.out.println("1. 仅搜索当前目录");
System.out.println("2. 搜索当前目录及子目录");
System.out.print("请选择搜索范围: ");
int scope;
try {
scope = Integer.parseInt(scanner.nextLine());
if (scope < 1 || scope > 2) {
System.out.println("请输入1或2!");
return;
}
} catch (NumberFormatException e) {
System.out.println("请输入有效的数字!");
return;
}
System.out.println("搜索结果:");
List<File> results = new ArrayList<>();
if (scope == 1) {
// 仅搜索当前目录
File currentDir = new File(currentPath);
File[] files = currentDir.listFiles();
if (files != null) {
for (File file : files) {
if (file.getName().toLowerCase().contains(keyword)) {
results.add(file);
}
}
}
} else {
// 搜索当前目录及子目录(递归)
searchRecursively(new File(currentPath), keyword, results);
}
if (results.isEmpty()) {
System.out.println("未找到匹配的文件/目录");
} else {
System.out.println("找到 " + results.size() + " 个匹配项:");
results.forEach(file -> {
String type = file.isDirectory() ? "[目录]" : "[文件]";
System.out.println(type + " " + file.getAbsolutePath());
});
}
}
// 递归搜索文件
private static void searchRecursively(File dir, String keyword, List<File> results) {
if (!dir.isDirectory()) {
return;
}
File[] files = dir.listFiles();
if (files == null) {
return;
}
for (File file : files) {
if (file.getName().toLowerCase().contains(keyword)) {
results.add(file);
}
if (file.isDirectory()) {
searchRecursively(file, keyword, results);
}
}
}
// 显示文件统计信息
private static void showFileStatistics() {
System.out.println("\n===== 文件统计信息 =====");
System.out.println("1. 按文件类型统计");
System.out.println("2. 按文件大小统计");
System.out.print("请选择统计方式: ");
int choice;
try {
choice = Integer.parseInt(scanner.nextLine());
if (choice < 1 || choice > 2) {
System.out.println("请输入1或2!");
return;
}
} catch (NumberFormatException e) {
System.out.println("请输入有效的数字!");
return;
}
// 收集当前目录及子目录的所有文件
List<File> allFiles = new ArrayList<>();
collectAllFiles(new File(currentPath), allFiles);
if (allFiles.isEmpty()) {
System.out.println("没有找到任何文件");
return;
}
if (choice == 1) {
// 按文件类型统计
System.out.println("\n按文件类型统计:");
allFiles.stream()
.filter(file -> file.isFile()) // 只统计文件
.map(file -> {
String name = file.getName();
int dotIndex = name.lastIndexOf('.');
return dotIndex > 0 ? name.substring(dotIndex) : "无扩展名";
})
.collect(Collectors.groupingBy(ext -> ext, Collectors.counting()))
.entrySet().stream()
.sorted((e1, e2) -> Long.compare(e2.getValue(), e1.getValue())) // 按数量降序
.forEach(entry -> System.out.println(" " + entry.getKey() + ": " + entry.getValue() + "个文件"));
} else {
// 按文件大小统计
System.out.println("\n按文件大小统计:");
long totalSize = allFiles.stream()
.filter(file -> file.isFile())
.mapToLong(File::length)
.sum();
System.out.println(" 总文件数量: " + allFiles.size() + "");
System.out.println(" 总文件大小: " + totalSize + " bytes");
// 大文件筛选大于1MB
long largeFileCount = allFiles.stream()
.filter(file -> file.isFile() && file.length() > 1024 * 1024)
.count();
System.out.println(" 大文件(>1MB)数量: " + largeFileCount + "");
}
}
// 收集所有文件(递归)
private static void collectAllFiles(File dir, List<File> files) {
if (!dir.isDirectory()) {
return;
}
File[] dirFiles = dir.listFiles();
if (dirFiles == null) {
return;
}
for (File file : dirFiles) {
if (file.isFile()) {
files.add(file);
} else if (file.isDirectory()) {
collectAllFiles(file, files);
}
}
}
// 批量操作
private static void batchOperations() {
System.out.println("\n===== 批量操作 =====");
System.out.println("1. 批量列出特定类型文件");
System.out.println("2. 批量删除特定类型文件");
System.out.print("请选择操作类型: ");
int choice;
try {
choice = Integer.parseInt(scanner.nextLine());
if (choice < 1 || choice > 2) {
System.out.println("请输入1或2!");
return;
}
} catch (NumberFormatException e) {
System.out.println("请输入有效的数字!");
return;
}
System.out.print("请输入文件扩展名(如txt, java无需输入.): ");
String ext = scanner.nextLine().trim().toLowerCase();
if (ext.isEmpty()) {
System.out.println("扩展名不能为空!");
return;
}
final String extension = ext;
// 使用文件过滤器筛选特定类型文件
File currentDir = new File(currentPath);
File[] targetFiles = currentDir.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
File file = new File(dir, name);
return file.isFile() && name.toLowerCase().endsWith("." + extension);
}
});
if (targetFiles == null || targetFiles.length == 0) {
System.out.println("未找到." + extension + "类型的文件");
return;
}
System.out.println("找到 " + targetFiles.length + " 个." + extension + "类型的文件:");
for (File file : targetFiles) {
System.out.println(" " + file.getName() + " (" + file.length() + " bytes)");
}
if (choice == 2) {
System.out.print("确定要删除这些文件吗? (y/n): ");
String confirm = scanner.nextLine().trim().toLowerCase();
if (confirm.equals("y")) {
int deletedCount = 0;
for (File file : targetFiles) {
if (file.delete()) {
deletedCount++;
}
}
System.out.println("已删除 " + deletedCount + " 个文件");
} else {
System.out.println("已取消删除操作");
}
}
}
}

View File

@@ -0,0 +1,62 @@
package com.inmind.s_test08;
import java.io.File;
/*
13.递归遍历文件夹的练习(重点)
需求:将D:\io_test里面的所有的子内容的名称都打印出来.
在遍历文件夹操作中,文件中不断地创建文件夹所以普通的循环遍历得子内容的代码实现不了
所以只能使用递归代码
遍历文件夹的递归代码:
1.结束条件:如果是文件就打印结束
2.如果是文件夹就继续遍历,如果是文件就打印结束
*/
public class ForeachFileDemo01 {
public static void main(String[] args) {
File file = new File("d:/io_test");
//定义出一个方法能够将指定的文件夹的内容都遍历出来
getFiles(file);
}
private static void getFiles(File file) {
//先把非法的情况都拦住
if (file == null||!file.exists()||file.isFile()){
return;
}
//io_test的所有的一级子内容对象
File[] files = file.listFiles();
if (files!=null||files.length > 0){
//遍历数组
for (File f : files) {
if (f.isDirectory()) {
System.out.println(f.getName());
//继续遍历明星
getFiles(f);
} else {
System.out.println(f.getName());
}
}
}
}
//继续遍历明星
private static void getMingXingFiles(File file) {
File[] files = file.listFiles();
for (File f : files) {
if (f.isDirectory()) {
System.out.println(f.getName());
//继续遍历女明星文件夹
//getNvMingxingFiles();
} else {
System.out.println(f.getName());
}
}
}
}

View File

@@ -0,0 +1,29 @@
package com.inmind.s_test12;
/*
enum是一种特殊的类
1.枚举类的第一行只能罗列一些名称,这些名称都是常量,并且每个常量都是枚举类的一个对象
2.枚举类的构造器都是私有的,因此枚举类对外不能创建对象
3.枚举是最终类,不能被继承
4.枚举类中,第二行开始,可以定义类的各种成员
5.编译器为枚举类新增了几个方法并且枚举类都是继承java.lang.Enum类的从enum类会继承一些方法
*/
public enum A {
X,Y("YYYY"),Z;
private String name;
A(){
this(null);
}
A(String name){
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

View File

@@ -0,0 +1,26 @@
package com.inmind.s_test12;
import java.util.Arrays;
public class Demo01 {
public static void main(String[] args) {
// A.Z = null;
A a1 = A.X;
A a2 = A.Y;
A a3 = A.Z;
System.out.println(a2.ordinal());
System.out.println(a1.ordinal());
System.out.println(a2.getName());
System.out.println(Arrays.toString(A.values()));
A a4 = A.valueOf("Y");
System.out.println(a4.getName());
method(A.Y);
}
public static void method(A a) {
System.out.println(a.getName());
}
}

View File

@@ -0,0 +1,231 @@
package com.inmind.s_test_02;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
// 商品接口:定义所有商品的共同属性和行为,作为泛型的边界
interface Product {
String getId(); // 获取商品ID
String getName(); // 获取商品名称
double getPrice(); // 获取商品价格
}
// 具体商品类:电子设备
class ElectronicProduct implements Product {
private String id; // 商品ID
private String name; // 商品名称
private double price; // 商品价格
private String brand; // 电子设备特有属性:品牌
// 构造方法:初始化电子设备信息
public ElectronicProduct(String id, String name, double price, String brand) {
this.id = id;
this.name = name;
this.price = price;
this.brand = brand;
}
// 实现Product接口的方法
public String getId() { return id; }
public String getName() { return name; }
public double getPrice() { return price; }
// 特有属性的getter方法
public String getBrand() { return brand; }
// 重写toString方法方便打印商品信息
@Override
public String toString() {
return "电子设备{ID=" + id + ", 名称=" + name + ", 价格=" + price + ", 品牌=" + brand + "}";
}
}
// 具体商品类:图书
class Book implements Product {
private String id; // 商品ID
private String name; // 商品名称
private double price; // 商品价格
private String author; // 图书特有属性:作者
// 构造方法:初始化图书信息
public Book(String id, String name, double price, String author) {
this.id = id;
this.name = name;
this.price = price;
this.author = author;
}
// 实现Product接口的方法
public String getId() { return id; }
public String getName() { return name; }
public double getPrice() { return price; }
// 特有属性的getter方法
public String getAuthor() { return author; }
// 重写toString方法方便打印商品信息
@Override
public String toString() {
return "图书{ID=" + id + ", 名称=" + name + ", 价格=" + price + ", 作者=" + author + "}";
}
}
// 库存记录类关联商品和库存信息使用泛型限定只能存储Product类型
class InventoryRecord<T extends Product> {
private T product; // 商品对象(泛型类型)
private int quantity; // 库存数量
private String warehouseLocation; // 仓库位置
// 构造方法:初始化库存记录
public InventoryRecord(T product, int quantity, String warehouseLocation) {
this.product = product;
this.quantity = quantity;
this.warehouseLocation = warehouseLocation;
}
// getter和setter方法
public T getProduct() { return product; }
public int getQuantity() { return quantity; }
public void setQuantity(int quantity) { this.quantity = quantity; }
public String getWarehouseLocation() { return warehouseLocation; }
}
// 泛型库存管理器核心业务类T限定为Product的子类
class InventoryManager<T extends Product> {
// 泛型集合:存储特定类型的库存记录,保证类型安全
private List<InventoryRecord<T>> inventoryList = new ArrayList<>();
/**
* 添加商品到库存
* 泛型特性确保只能添加指定类型的商品
*/
public void addProduct(T product, int quantity, String location) {
// 查找是否已存在该商品的库存记录
Optional<InventoryRecord<T>> existingRecord = findRecordById(product.getId());
if (existingRecord.isPresent()) {
// 已存在则更新库存数量
existingRecord.get().setQuantity(existingRecord.get().getQuantity() + quantity);
} else {
// 不存在则创建新的库存记录并添加到列表
inventoryList.add(new InventoryRecord<>(product, quantity, location));
}
}
/**
* 从库存中移除商品
* @param productId 商品ID
* @param quantity 要移除的数量
* @return 是否移除成功
*/
public boolean removeProduct(String productId, int quantity) {
// 查找商品库存记录
Optional<InventoryRecord<T>> record = findRecordById(productId);
if (record.isPresent()) {
InventoryRecord<T> inventoryRecord = record.get();
// 检查库存是否充足
if (inventoryRecord.getQuantity() >= quantity) {
// 更新库存数量
inventoryRecord.setQuantity(inventoryRecord.getQuantity() - quantity);
// 如果库存为0从列表中移除该记录
if (inventoryRecord.getQuantity() == 0) {
inventoryList.remove(inventoryRecord);
}
return true;
}
}
// 商品不存在或库存不足返回false
return false;
}
/**
* 根据商品ID查找库存记录
* @param productId 商品ID
* @return 包含库存记录的Optional对象
*/
public Optional<InventoryRecord<T>> findRecordById(String productId) {
// 遍历库存列表查找匹配的商品
for (InventoryRecord<T> record : inventoryList) {
if (record.getProduct().getId().equals(productId)) {
return Optional.of(record); // 找到则返回包含该记录的Optional
}
}
return Optional.empty(); // 未找到则返回空Optional
}
/**
* 计算库存总量
* @return 所有商品的库存总和
*/
public int getTotalQuantity() {
int total = 0;
// 遍历库存列表累加数量
for (InventoryRecord<T> record : inventoryList) {
total += record.getQuantity();
}
return total;
}
/**
* 显示所有库存记录
*/
public void displayAllInventory() {
System.out.println("=== 库存记录 ===");
// 遍历并打印所有库存信息
for (InventoryRecord<T> record : inventoryList) {
System.out.println(record.getProduct() +
", 库存数量: " + record.getQuantity() +
", 存放位置: " + record.getWarehouseLocation());
}
}
}
// 测试类:演示库存管理系统的使用
public class InventorySystem {
public static void main(String[] args) {
// 1. 创建电子设备库存管理器泛型类型指定为ElectronicProduct
InventoryManager<ElectronicProduct> electronicManager = new InventoryManager<>();
// 向电子设备库存添加商品
electronicManager.addProduct(
new ElectronicProduct("E001", "智能手机", 5999.99, "华为"),
50, "A区-101" // 数量50存放位置A区-101
);
electronicManager.addProduct(
new ElectronicProduct("E002", "笔记本电脑", 7999.99, "苹果"),
30, "A区-102" // 数量30存放位置A区-102
);
// 显示电子设备库存总量和详细记录
System.out.println("电子设备库存总量: " + electronicManager.getTotalQuantity());
electronicManager.displayAllInventory();
// 从电子设备库存中移除部分商品
electronicManager.removeProduct("E001", 10); // 移除10台智能手机
System.out.println("\n移除10台智能手机后:");
electronicManager.displayAllInventory();
// 2. 创建图书库存管理器泛型类型指定为Book
InventoryManager<Book> bookManager = new InventoryManager<>();
// 向图书库存添加商品
bookManager.addProduct(
new Book("B001", "Java编程思想", 108.0, "Bruce Eckel"),
100, "B区-201" // 数量100存放位置B区-201
);
bookManager.addProduct(
new Book("B002", "设计模式", 89.0, "Erich Gamma"),
80, "B区-202" // 数量80存放位置B区-202
);
// 显示图书库存总量和详细记录
System.out.println("\n图书库存总量: " + bookManager.getTotalQuantity());
bookManager.displayAllInventory();
// 演示泛型的类型安全:以下代码会编译错误
// 因为electronicManager只能处理ElectronicProduct类型不能添加Book类型
// electronicManager.addProduct(new Book("B001", "错误的类型", 0, ""), 1, "");
}
}

View File

@@ -0,0 +1,239 @@
package com.inmind.s_test_0202;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
// 商品接口:定义所有商品的共同属性和行为,作为泛型的边界
interface Product {
String getId(); // 获取商品ID
String getName(); // 获取商品名称
double getPrice(); // 获取商品价格
}
// 具体商品类:电子设备
class ElectronicProduct implements Product {
private String id; // 商品ID
private String name; // 商品名称
private double price; // 商品价格
private String brand; // 电子设备特有属性:品牌
// 构造方法:初始化电子设备信息
public ElectronicProduct(String id, String name, double price, String brand) {
this.id = id;
this.name = name;
this.price = price;
this.brand = brand;
}
// 实现Product接口的方法
public String getId() { return id; }
public String getName() { return name; }
public double getPrice() { return price; }
// 特有属性的getter方法
public String getBrand() { return brand; }
// 重写toString方法方便打印商品信息
@Override
public String toString() {
return "电子设备{ID=" + id + ", 名称=" + name + ", 价格=" + price + ", 品牌=" + brand + "}";
}
}
// 具体商品类:图书
class Book implements Product {
private String id; // 商品ID
private String name; // 商品名称
private double price; // 商品价格
private String author; // 图书特有属性:作者
// 构造方法:初始化图书信息
public Book(String id, String name, double price, String author) {
this.id = id;
this.name = name;
this.price = price;
this.author = author;
}
// 实现Product接口的方法
public String getId() { return id; }
public String getName() { return name; }
public double getPrice() { return price; }
// 特有属性的getter方法
public String getAuthor() { return author; }
// 重写toString方法方便打印商品信息
@Override
public String toString() {
return "图书{ID=" + id + ", 名称=" + name + ", 价格=" + price + ", 作者=" + author + "}";
}
}
// 库存记录类关联商品和库存信息使用泛型限定只能存储Product类型
class InventoryRecord<T extends Product> {
private T product; // 商品对象(泛型类型)
private int quantity; // 库存数量
private String warehouseLocation; // 仓库位置
// 构造方法:初始化库存记录
public InventoryRecord(T product, int quantity, String warehouseLocation) {
this.product = product;
this.quantity = quantity;
this.warehouseLocation = warehouseLocation;
}
// getter和setter方法
public T getProduct() { return product; }
public int getQuantity() { return quantity; }
public void setQuantity(int quantity) { this.quantity = quantity; }
public String getWarehouseLocation() { return warehouseLocation; }
}
// 泛型库存管理器核心业务类T限定为Product的子类
class InventoryManager<T extends Product> {
// 泛型集合:存储特定类型的库存记录,保证类型安全
private List<InventoryRecord<T>> inventoryList = new ArrayList<>();
/**
* 根据商品ID查找库存记录
* @param productId 商品ID
* @return 找到的库存记录未找到则返回null
*/
public InventoryRecord<T> findRecordById(String productId) {
// 遍历库存列表查找匹配的商品
for (InventoryRecord<T> record : inventoryList) {
if (record.getProduct().getId().equals(productId)) {
return record; // 找到则返回该记录
}
}
return null; // 未找到则返回null
}
/**
* 添加商品到库存
* 泛型特性确保只能添加指定类型的商品
*/
public void addProduct(T product, int quantity, String location) {
// 查找是否已存在该商品的库存记录不使用Optional直接返回对象或null
InventoryRecord<T> existingRecord = findRecordById(product.getId());
if (existingRecord != null) {
// 已存在则更新库存数量
existingRecord.setQuantity(existingRecord.getQuantity() + quantity);
} else {
// 不存在则创建新的库存记录并添加到列表
inventoryList.add(new InventoryRecord<>(product, quantity, location));
}
}
/**
* 从库存中移除商品
* @param productId 商品ID
* @param quantity 要移除的数量
* @return 是否移除成功
*/
public boolean removeProduct(String productId, int quantity) {
// 查找商品库存记录不使用Optional
InventoryRecord<T> record = findRecordById(productId);
if (record != null) {
// 检查库存是否充足
if (record.getQuantity() >= quantity) {
// 更新库存数量
record.setQuantity(record.getQuantity() - quantity);
// 如果库存为0从列表中移除该记录
if (record.getQuantity() == 0) {
inventoryList.remove(record);
}
return true;
}
}
// 商品不存在或库存不足返回false
return false;
}
/**
* 计算库存总量
* @return 所有商品的库存总和
*/
public int getTotalQuantity() {
int total = 0;
// 遍历库存列表累加数量
for (InventoryRecord<T> record : inventoryList) {
total += record.getQuantity();
}
return total;
}
/**
* 显示所有库存记录
*/
public void displayAllInventory() {
System.out.println("=== 库存记录 ===");
// 遍历并打印所有库存信息
for (InventoryRecord<T> record : inventoryList) {
System.out.println(record.getProduct() +
", 库存数量: " + record.getQuantity() +
", 存放位置: " + record.getWarehouseLocation());
}
}
}
// 测试类:演示库存管理系统的使用
public class InventorySystem1 {
public static void main(String[] args) {
// 1. 创建电子设备库存管理器泛型类型指定为ElectronicProduct
InventoryManager<ElectronicProduct> electronicManager = new InventoryManager<>();
// 向电子设备库存添加商品
electronicManager.addProduct(
new ElectronicProduct("E001", "智能手机", 5999.99, "华为"),
50, "A区-101" // 数量50存放位置A区-101
);
electronicManager.addProduct(
new ElectronicProduct("E002", "笔记本电脑", 7999.99, "苹果"),
30, "A区-102" // 数量30存放位置A区-102
);
// 显示电子设备库存总量和详细记录
System.out.println("电子设备库存总量: " + electronicManager.getTotalQuantity());
electronicManager.displayAllInventory();
// 从电子设备库存中移除部分商品
electronicManager.removeProduct("E001", 10); // 移除10台智能手机
System.out.println("\n移除10台智能手机后:");
electronicManager.displayAllInventory();
// 2. 创建图书库存管理器泛型类型指定为Book
InventoryManager<Book> bookManager = new InventoryManager<>();
// 向图书库存添加商品
bookManager.addProduct(
new Book("B001", "Java编程思想", 108.0, "Bruce Eckel"),
100, "B区-201" // 数量100存放位置B区-201
);
bookManager.addProduct(
new Book("B002", "设计模式", 89.0, "Erich Gamma"),
80, "B区-202" // 数量80存放位置B区-202
);
// 显示图书库存总量和详细记录
System.out.println("\n图书库存总量: " + bookManager.getTotalQuantity());
bookManager.displayAllInventory();
// 演示泛型的类型安全:以下代码会编译错误
// 因为electronicManager只能处理ElectronicProduct类型不能添加Book类型
// electronicManager.addProduct(new Book("B001", "错误的类型", 0, ""), 1, "");
}
}

View File

@@ -0,0 +1,131 @@
package com.inmind.s_test_03;
import java.util.HashSet;
import java.util.Set;
/**
* 学生实体类
* 存储学生基本信息及所选课程
*/
public class Student {
// 学号
private String id;
// 姓名
private String name;
// 年龄
private int age;
// 成绩
private double score;
// 所选课程使用Set确保课程不重复
private Set<String> courses;
/**
* 构造方法
* @param id 学号
* @param name 姓名
* @param age 年龄
*/
public Student(String id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
this.courses = new HashSet<String>(); // 初始化课程集合
this.score = 0.0; // 初始成绩为0
}
/**
* 添加课程
* @param course 课程名称
*/
public void addCourse(String course) {
courses.add(course); // 利用Set特性自动去重
}
// getter和setter方法
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public double getScore() {
return score;
}
public void setScore(double score) {
this.score = score;
}
public Set<String> getCourses() {
// 返回一个新的HashSet避免外部直接修改内部集合
return new HashSet<String>(courses);
}
/**
* 重写equals方法根据学号判断对象是否相等
* @param obj 比较的对象
* @return 是否相等
*/
@Override
public boolean equals(Object obj) {
if (this == obj) { // 引用相同对象
return true;
}
if (obj == null) { // 比较对象为null
return false;
}
if (getClass() != obj.getClass()) { // 类型不同
return false;
}
Student other = (Student) obj; // 类型转换
if (id == null) { // 当前对象学号为null
if (other.id != null) { // 比较对象学号不为null
return false;
}
} else if (!id.equals(other.id)) { // 学号不相等
return false;
}
return true;
}
/**
* 重写hashCode方法与equals保持一致
* @return 哈希值
*/
@Override
public int hashCode() {
final int prime = 31; // 质数,用于计算哈希值
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode()); // 基于学号计算哈希值
return result;
}
/**
* 重写toString方法方便打印学生信息
* @return 学生信息字符串
*/
@Override
public String toString() {
return "学号:" + id + ", 姓名:" + name + ", 年龄:" + age +
", 成绩:" + score + ", 所选课程:" + courses;
}
}

View File

@@ -0,0 +1,87 @@
package com.inmind.s_test_03;
import java.util.Comparator;
/**
* 学生比较器类
* 实现不同的比较策略
*/
public class StudentComparator {
/**
* 按学号升序排序
* @return 比较器实例
*/
public static Comparator<Student> byIdAsc() {
// 返回匿名内部类实现的Comparator
return new Comparator<Student>() {
@Override
public int compare(Student s1, Student s2) {
// 比较两个学生的学号
return s1.getId().compareTo(s2.getId());
}
};
}
/**
* 按姓名升序排序
* @return 比较器实例
*/
public static Comparator<Student> byNameAsc() {
return new Comparator<Student>() {
@Override
public int compare(Student s1, Student s2) {
// 比较两个学生的姓名
return s1.getName().compareTo(s2.getName());
}
};
}
/**
* 按成绩降序排序
* @return 比较器实例
*/
public static Comparator<Student> byScoreDesc() {
return new Comparator<Student>() {
@Override
public int compare(Student s1, Student s2) {
// 成绩高的排在前面(降序)
return Double.compare(s2.getScore(), s1.getScore());
}
};
}
/**
* 先按成绩降序,成绩相同则按姓名升序
* @return 比较器实例
*/
public static Comparator<Student> byScoreDescAndNameAsc() {
return new Comparator<Student>() {
@Override
public int compare(Student s1, Student s2) {
// 先比较成绩
int scoreCompare = Double.compare(s2.getScore(), s1.getScore());
if (scoreCompare != 0) { // 成绩不同
return scoreCompare;
} else { // 成绩相同则比较姓名
return s1.getName().compareTo(s2.getName());
}
}
};
}
/**
* 按年龄升序排序
* @return 比较器实例
*/
public static Comparator<Student> byAgeAsc() {
return new Comparator<Student>() {
@Override
public int compare(Student s1, Student s2) {
// 比较两个学生的年龄
return Integer.compare(s1.getAge(), s2.getAge());
}
};
}
}

View File

@@ -0,0 +1,211 @@
package com.inmind.s_test_03;
import java.util.*;
/**
* 学生管理系统
* 演示List、Set集合的使用以及Comparator和Collections工具类的应用
*/
public class StudentManager {
public static final String COURSE_JAVA = "Java编程";
// 存储学生列表使用List允许重复添加检测和有序访问
private List<Student> students;
// 存储所有可选课程使用Set确保课程不重复
private Set<String> allCourses;
/**
* 构造方法,初始化集合
*/
public StudentManager() {
students = new ArrayList<Student>(); // 初始化学生列表
allCourses = new HashSet<String>(); // 初始化课程集合
initData(); // 初始化测试数据
}
/**
* 初始化测试数据
*/
private void initData() {
// 添加课程
allCourses.add(COURSE_JAVA);
allCourses.add("数据结构");
allCourses.add("计算机网络");
allCourses.add("数据库原理");
allCourses.add("操作系统");
// 添加学生1
Student s1 = new Student("2023001", "张三", 20);
s1.addCourse("Java编程");
s1.addCourse("数据结构");
s1.setScore(85.5);
students.add(s1);
// 添加学生2
Student s2 = new Student("2023002", "李四", 21);
s2.addCourse("Java编程");
s2.addCourse("数据库原理");
s2.setScore(92.0);
students.add(s2);
// 添加学生3
Student s3 = new Student("2023003", "王五", 19);
s3.addCourse("计算机网络");
s3.addCourse("操作系统");
s3.setScore(78.5);
students.add(s3);
// 添加学生4
Student s4 = new Student("2023004", "赵六", 20);
s4.addCourse("数据结构");
s4.addCourse("数据库原理");
s4.setScore(88.0);
students.add(s4);
}
/**
* 添加学生
* @param student 要添加的学生对象
* @return 添加成功返回true已存在返回false
*/
public boolean addStudent(Student student) {
// 检查学生是否已存在依赖Student类重写的equals方法
if (!students.contains(student)) {
students.add(student);
return true;
}
return false;
}
/**
* 显示所有学生信息
*/
public void showAllStudents() {
System.out.println("\n===== 所有学生信息 =====");
// 使用增强for循环遍历学生列表
for (Student student : students) {
System.out.println(student);
}
}
/**
* 按条件排序并显示学生信息
* @param comparator 比较器,定义排序规则
* @param sortType 排序类型描述,用于输出显示
*/
public void sortAndShowStudents(Comparator<Student> comparator, String sortType) {
// 创建列表副本进行排序,避免修改原列表顺序
List<Student> sortedList = new ArrayList<Student>(students);
// 使用Collections工具类进行排序
Collections.sort(sortedList, comparator);
System.out.println("\n===== 按" + sortType + "排序的学生信息 =====");
// 遍历排序后的列表
for (Student student : sortedList) {
System.out.println(student);
}
}
/**
* 根据学号查找学生
* @param id 要查找的学号
* @return 找到的学生对象未找到返回null
*/
public Student findStudentById(String id) {
// 创建列表副本并按学号排序(二分查找需要有序列表)
List<Student> sortedById = new ArrayList<Student>(students);
Collections.sort(sortedById, StudentComparator.byIdAsc());
// 使用Collections的binarySearch进行二分查找
int index = Collections.binarySearch(sortedById,
new Student(id, "", 0), // 临时创建用于比较的学生对象
StudentComparator.byIdAsc()); // 使用学号比较器
// 索引>=0表示找到返回对应学生对象
return index >= 0 ? sortedById.get(index) : null;
}
/**
* 获取选修某门课程的所有学生
* @param course 课程名称
* @return 选修该课程的学生集合
*/
public Set<Student> getStudentsByCourse(String course) {
Set<Student> result = new HashSet<Student>();
// 遍历所有学生
for (Student student : students) {
// 检查学生是否选修了该课程
if (student.getCourses().contains(course)) {
result.add(student);
}
}
return result;
}
/**
* 计算学生平均年龄
* @return 平均年龄
*/
public double getAverageAge() {
if (students.isEmpty()) { // 学生列表为空时返回0
return 0;
}
int totalAge = 0;
// 遍历所有学生,累加年龄
for (Student student : students) {
totalAge += student.getAge();
}
// 计算并返回平均年龄
return (double) totalAge / students.size();
}
/**
* 主方法,演示系统功能
* @param args 命令行参数
*/
public static void main(String[] args) {
// 创建学生管理系统实例
StudentManager manager = new StudentManager();
// 显示所有学生
manager.showAllStudents();
// 按不同条件排序并显示
manager.sortAndShowStudents(StudentComparator.byIdAsc(), "学号升序");
manager.sortAndShowStudents(StudentComparator.byNameAsc(), "姓名升序");
manager.sortAndShowStudents(StudentComparator.byScoreDesc(), "成绩降序");
manager.sortAndShowStudents(StudentComparator.byScoreDescAndNameAsc(), "成绩降序+姓名升序");
manager.sortAndShowStudents(StudentComparator.byAgeAsc(), "年龄升序");
// 查找指定学号的学生
String searchId = "2023002";
Student found = manager.findStudentById(searchId);
System.out.println("\n查找学号为" + searchId + "的学生: " +
(found != null ? found.getName() : "未找到"));
// 查找选修特定课程的学生
String course = "Java编程";
Set<Student> javaStudents = manager.getStudentsByCourse(course);
System.out.println("\n选修" + course + "的学生有" + javaStudents.size() + "人:");
// 使用迭代器遍历Set集合
Iterator<Student> iterator = javaStudents.iterator();
while (iterator.hasNext()) {
Student student = iterator.next();
System.out.println(student.getName());
}
// 统计并显示平均年龄
System.out.println("\n学生平均年龄: " + String.format("%.1f", manager.getAverageAge()));
// 添加新学生
Student newStudent = new Student("2023005", "钱七", 22);
newStudent.addCourse("操作系统");
newStudent.setScore(90.5);
boolean added = manager.addStudent(newStudent);
System.out.println("\n添加新学生" + newStudent.getName() + ": " + (added ? "成功" : "失败(已存在)"));
// 再次显示所有学生,验证新学生是否添加成功
manager.showAllStudents();
}
}

View File

@@ -0,0 +1,202 @@
package com.inmind.s_test_04;
import java.util.*;
/**
* 极简版购物系统
* 功能:浏览商品、搜索商品、管理购物车
*/
public class CartSystem {
// 商品列表(单列集合)
private static List<Product> products = new ArrayList<>();
// 购物车(双列集合:商品-数量)
private static Map<Product, Integer> cart = new HashMap<>();
private static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
// 初始化商品数据
initProducts();
System.out.println("===== 简易购物系统 =====");
showMainMenu();
}
// 初始化商品
private static void initProducts() {
products.add(new Product("P01", "笔记本电脑", 5999.99, "电子产品", 10));
products.add(new Product("P02", "机械键盘", 299.99, "电脑配件", 20));
products.add(new Product("P03", "无线鼠标", 129.99, "电脑配件", 30));
products.add(new Product("P04", "蓝牙耳机", 799.99, "音频设备", 15));
products.add(new Product("P05", "智能手机", 3999.99, "电子产品", 25));
}
// 显示主菜单
private static void showMainMenu() {
while (true) {
System.out.println("\n===== 主菜单 =====");
System.out.println("1. 浏览所有商品");
System.out.println("2. 搜索商品");
System.out.println("3. 查看购物车");
System.out.println("4. 添加商品到购物车");
System.out.println("5. 修改购物车商品数量");
System.out.println("6. 清空购物车");
System.out.println("7. 退出");
System.out.print("请选择: ");
int choice = getIntInput();
if (choice < 1 || choice > 7) {
System.out.println("无效选择,请重试");
continue;
}
switch (choice) {
case 1: browseProducts(); break;
case 2: searchProducts(); break;
case 3: viewCart(); break;
case 4: addToCart(); break;
case 5: updateCartQuantity(); break;
case 6: cart.clear(); System.out.println("购物车已清空"); break;
case 7: System.out.println("谢谢使用,再见!"); scanner.close(); return;
}
}
}
// 浏览所有商品
private static void browseProducts() {
System.out.println("\n===== 所有商品 =====");
for (int i = 0; i < products.size(); i++) {
System.out.println(products.get(i));
}
}
// 搜索商品
private static void searchProducts() {
System.out.print("请输入商品名称关键字: ");
String keyword = scanner.nextLine().toLowerCase();
List<Product> result = new ArrayList<>();
for (int i = 0; i < products.size(); i++) {
Product p = products.get(i);
if (p.getName().toLowerCase().contains(keyword)) {
result.add(p);
}
}
System.out.println("\n===== 搜索结果 =====");
if (result.isEmpty()) {
System.out.println("没有找到匹配的商品");
} else {
for (int i = 0; i < result.size(); i++) {
System.out.println(result.get(i));
}
}
}
// 查看购物车
private static void viewCart() {
System.out.println("\n===== 购物车 =====");
if (cart.isEmpty()) {
System.out.println("购物车是空的");
return;
}
double total = 0;
// 使用迭代器遍历Map
Iterator<Map.Entry<Product, Integer>> iterator = cart.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<Product, Integer> entry = iterator.next();
Product p = entry.getKey();
int qty = entry.getValue();
double subtotal = p.getPrice() * qty;
total += subtotal;
System.out.printf("%s, 数量: %d, 小计: ¥%.2f%n",
p.getName(), qty, subtotal);
}
System.out.printf("购物车总计: ¥%.2f%n", total);
}
// 添加商品到购物车
private static void addToCart() {
System.out.print("请输入商品ID: ");
String id = scanner.nextLine();
// 查找商品
Product product = null;
for (int i = 0; i < products.size(); i++) {
if (products.get(i).getId().equals(id)) {
product = products.get(i);
break;
}
}
if (product == null) {
System.out.println("未找到该商品");
return;
}
System.out.print("请输入购买数量: ");
int quantity = getIntInput();
if (quantity <= 0) {
System.out.println("数量必须大于0");
return;
}
// 检查库存
if (quantity > product.getStock()) {
System.out.println("库存不足,当前库存: " + product.getStock());
return;
}
// 添加到购物车
if (cart.containsKey(product)) {
cart.put(product, cart.get(product) + quantity);
} else {
cart.put(product, quantity);
}
System.out.println("已添加到购物车");
}
// 修改购物车商品数量
private static void updateCartQuantity() {
System.out.print("请输入要修改的商品ID: ");
String id = scanner.nextLine();
// 查找购物车中的商品
Product targetProduct = null;
Iterator<Map.Entry<Product, Integer>> iterator = cart.entrySet().iterator();
while (iterator.hasNext()) {
Product p = iterator.next().getKey();
if (p.getId().equals(id)) {
targetProduct = p;
break;
}
}
if (targetProduct == null) {
System.out.println("购物车中没有该商品");
return;
}
System.out.print("请输入新的数量: ");
int newQty = getIntInput();
if (newQty <= 0) {
cart.remove(targetProduct);
System.out.println("已从购物车移除该商品");
} else if (newQty > targetProduct.getStock()) {
System.out.println("库存不足,当前库存: " + targetProduct.getStock());
} else {
cart.put(targetProduct, newQty);
System.out.println("数量已更新");
}
}
// 获取整数输入并处理异常
private static int getIntInput() {
try {
return Integer.parseInt(scanner.nextLine());
} catch (NumberFormatException e) {
return -1;
}
}
}

View File

@@ -0,0 +1,62 @@
package com.inmind.s_test_04;
/**
* 商品类,存储商品基本信息
*/
public class Product {
private String id; // 商品ID
private String name; // 商品名称
private double price; // 商品价格
private String category; // 商品分类
private int stock; // 库存数量
public Product(String id, String name, double price, String category, int stock) {
this.id = id;
this.name = name;
this.price = price;
this.category = category;
this.stock = stock;
}
// getter方法
public String getId() {
return id;
}
public String getName() {
return name;
}
public double getPrice() {
return price;
}
public String getCategory() {
return category;
}
public int getStock() {
return stock;
}
@Override
public String toString() {
return "ID: "+this.id+", 名称: "+this.name+", 价格: ¥"+this.price+", 分类: "+this.category+", 库存: "+this.stock;
}
// 重写equals和hashCode确保在集合中正确比较商品对象
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Product product = (Product) o;
return id.equals(product.id);
}
@Override
public int hashCode() {
return id.hashCode();
}
}

View File

@@ -0,0 +1,344 @@
package com.inmind.s_test_04;
import java.util.*;
/**
* 购物系统主类不使用lambda表达式
*/
public class ShoppingSystem {
// 使用List存储所有商品单列集合应用
private static List<Product> products = new ArrayList<>();
// 使用Map实现购物车双列集合应用商品-数量)
private static Map<Product, Integer> shoppingCart = new HashMap<>();
private static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
// 初始化商品数据
initProducts();
System.out.println("===== 欢迎使用简易购物车系统 =====");
// 显示主菜单
showMainMenu();
}
// 初始化商品数据
private static void initProducts() {
products.add(new Product("P001", "笔记本电脑", 5999.99, "电子产品", 10));
products.add(new Product("P002", "机械键盘", 299.99, "电脑配件", 20));
products.add(new Product("P003", "无线鼠标", 129.99, "电脑配件", 30));
products.add(new Product("P004", "蓝牙耳机", 799.99, "音频设备", 15));
products.add(new Product("P005", "智能手机", 3999.99, "电子产品", 25));
products.add(new Product("P006", "游戏手柄", 349.99, "游戏设备", 18));
products.add(new Product("P007", "移动硬盘", 499.99, "存储设备", 12));
}
// 显示主菜单
private static void showMainMenu() {
while (true) {
System.out.println("\n===== 主菜单 =====");
System.out.println("1. 浏览所有商品");
System.out.println("2. 按分类浏览商品");
System.out.println("3. 搜索商品");
System.out.println("4. 查看购物车");
System.out.println("5. 添加商品到购物车");
System.out.println("6. 修改购物车商品数量");
System.out.println("7. 从购物车删除商品");
System.out.println("8. 清空购物车");
System.out.println("9. 退出系统");
System.out.print("请选择操作(1-9): ");
int choice;
try {
choice = Integer.parseInt(scanner.nextLine());
} catch (NumberFormatException e) {
System.out.println("输入错误请输入数字1-9");
continue;
}
switch (choice) {
case 1:
browseAllProducts();
break;
case 2:
browseProductsByCategory();
break;
case 3:
searchProducts();
break;
case 4:
viewShoppingCart();
break;
case 5:
addToCart();
break;
case 6:
updateCartItemQuantity();
break;
case 7:
removeFromCart();
break;
case 8:
clearCart();
break;
case 9:
System.out.println("感谢使用,再见!");
scanner.close();
return;
default:
System.out.println("无效选择请输入1-9之间的数字");
}
}
}
// 浏览所有商品
private static void browseAllProducts() {
System.out.println("\n===== 所有商品 =====");
for (Product product : products) {
System.out.println(product);
}
}
// 按分类浏览商品
private static void browseProductsByCategory() {
// 使用Map对商品进行分类键为分类名称值为该分类下的商品列表
Map<String, List<Product>> productsByCategory = new HashMap<>();
// 遍历商品列表,将商品按分类分组
for (Product product : products) {
String category = product.getCategory();
// 检查该分类是否已在Map中
if (!productsByCategory.containsKey(category)) {
// 如果不在则创建新的列表并放入Map
productsByCategory.put(category, new ArrayList<Product>());
}
// 将商品添加到对应分类的列表中
productsByCategory.get(category).add(product);
}
// 显示所有分类
System.out.println("\n===== 商品分类 =====");
int index = 1;
List<String> categories = new ArrayList<>();
// 使用迭代器遍历Map的键集
Iterator<String> categoryIterator = productsByCategory.keySet().iterator();
while (categoryIterator.hasNext()) {
String category = categoryIterator.next();
categories.add(category);
System.out.println(index + ". " + category);
index++;
}
// 选择分类
System.out.print("请选择要查看的分类(输入序号): ");
try {
int choice = Integer.parseInt(scanner.nextLine());
if (choice < 1 || choice > categories.size()) {
System.out.println("无效的分类序号");
return;
}
String selectedCategory = categories.get(choice - 1);
System.out.println("\n===== " + selectedCategory + " =====");
// 显示选中分类下的所有商品
List<Product> categoryProducts = productsByCategory.get(selectedCategory);
for (Product product : categoryProducts) {
System.out.println(product);
}
} catch (NumberFormatException e) {
System.out.println("输入错误,请输入数字");
}
}
// 搜索商品
private static void searchProducts() {
System.out.print("请输入商品名称关键字: ");
String keyword = scanner.nextLine().toLowerCase();
List<Product> result = new ArrayList<>();
// 遍历商品列表查找匹配的商品
for (Product product : products) {
if (product.getName().toLowerCase().contains(keyword)) {
result.add(product);
}
}
System.out.println("\n===== 搜索结果 =====");
if (result.isEmpty()) {
System.out.println("没有找到匹配的商品");
} else {
for (Product product : result) {
System.out.println(product);
}
}
}
// 查看购物车
private static void viewShoppingCart() {
System.out.println("\n===== 我的购物车 =====");
if (shoppingCart.isEmpty()) {
System.out.println("购物车是空的");
return;
}
double total = 0;
// 使用迭代器遍历购物车中的商品
Iterator<Map.Entry<Product, Integer>> iterator = shoppingCart.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<Product, Integer> entry = iterator.next();
Product product = entry.getKey();
int quantity = entry.getValue();
double subtotal = product.getPrice() * quantity;
total += subtotal;
System.out.printf("ID: %s, 名称: %s, 单价: ¥%.2f, 数量: %d, 小计: ¥%.2f%n",
product.getId(), product.getName(), product.getPrice(),
quantity, subtotal);
}
System.out.printf("购物车总金额: ¥%.2f%n", total);
}
// 添加商品到购物车
private static void addToCart() {
System.out.print("请输入要添加的商品ID: ");
String productId = scanner.nextLine();
// 查找商品
Product foundProduct = null;
for (Product product : products) {
if (product.getId().equals(productId)) {
foundProduct = product;
break;
}
}
if (foundProduct == null) {
System.out.println("没有找到该商品");
return;
}
System.out.print("请输入购买数量: ");
try {
int quantity = Integer.parseInt(scanner.nextLine());
if (quantity <= 0) {
System.out.println("数量必须大于0");
return;
}
if (quantity > foundProduct.getStock()) {
System.out.println("库存不足,当前库存: " + foundProduct.getStock());
return;
}
// 检查商品是否已在购物车中
if (shoppingCart.containsKey(foundProduct)) {
// 如果已存在,更新数量
int currentQuantity = shoppingCart.get(foundProduct);
shoppingCart.put(foundProduct, currentQuantity + quantity);
System.out.println("商品数量已更新,当前数量: " + (currentQuantity + quantity));
} else {
// 如果不存在,添加到购物车
shoppingCart.put(foundProduct, quantity);
System.out.println("商品已添加到购物车");
}
} catch (NumberFormatException e) {
System.out.println("输入错误,请输入数字");
}
}
// 修改购物车商品数量
private static void updateCartItemQuantity() {
if (shoppingCart.isEmpty()) {
System.out.println("购物车是空的");
return;
}
System.out.print("请输入要修改数量的商品ID: ");
String productId = scanner.nextLine();
// 查找购物车中的商品
Product foundProduct = null;
Iterator<Product> iterator = shoppingCart.keySet().iterator();
while (iterator.hasNext()) {
Product product = iterator.next();
if (product.getId().equals(productId)) {
foundProduct = product;
break;
}
}
if (foundProduct == null) {
System.out.println("购物车中没有该商品");
return;
}
System.out.print("请输入新的数量: ");
try {
int newQuantity = Integer.parseInt(scanner.nextLine());
if (newQuantity <= 0) {
System.out.println("数量必须大于0已从购物车中删除该商品");
shoppingCart.remove(foundProduct);
return;
}
if (newQuantity > foundProduct.getStock()) {
System.out.println("库存不足,当前库存: " + foundProduct.getStock());
return;
}
shoppingCart.put(foundProduct, newQuantity);
System.out.println("商品数量已更新");
} catch (NumberFormatException e) {
System.out.println("输入错误,请输入数字");
}
}
// 从购物车删除商品
private static void removeFromCart() {
if (shoppingCart.isEmpty()) {
System.out.println("购物车是空的");
return;
}
System.out.print("请输入要删除的商品ID: ");
String productId = scanner.nextLine();
// 查找购物车中的商品
Product foundProduct = null;
Iterator<Product> iterator = shoppingCart.keySet().iterator();
while (iterator.hasNext()) {
Product product = iterator.next();
if (product.getId().equals(productId)) {
foundProduct = product;
break;
}
}
if (foundProduct == null) {
System.out.println("购物车中没有该商品");
return;
}
shoppingCart.remove(foundProduct);
System.out.println("商品已从购物车中删除");
}
// 清空购物车
private static void clearCart() {
if (shoppingCart.isEmpty()) {
System.out.println("购物车已经是空的");
return;
}
System.out.print("确定要清空购物车吗?(y/n): ");
String confirm = scanner.nextLine();
if (confirm.equalsIgnoreCase("y")) {
shoppingCart.clear();
System.out.println("购物车已清空");
} else {
System.out.println("已取消清空操作");
}
}
}

View File

@@ -0,0 +1,71 @@
package com.inmind.s_test_044;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* 订单类,处理订单信息
*/
public class Order {
private String id; // 订单ID
private User user; // 下单用户
private List<OrderItem> items; // 订单商品列表
private double totalAmount; // 订单总金额
private Date createTime; // 创建时间
public Order(String id, User user) {
this.id = id;
this.user = user;
this.items = new ArrayList<>();
this.createTime = new Date();
this.totalAmount = 0;
}
// 添加商品到订单
public void addOrderItem(Product product, int quantity) {
OrderItem item = new OrderItem(product, quantity);
items.add(item);
totalAmount += item.getSubtotal();
}
// 显示订单信息
public void displayOrder() {
System.out.println("\n===== 订单信息 =====");
System.out.println("订单ID: " + id);
System.out.println("用户: " + user.getUsername());
System.out.println("创建时间: " + createTime);
System.out.println("商品列表:");
for (OrderItem item : items) {
System.out.println(item);
}
System.out.printf("订单总金额: ¥%.2f%n", totalAmount);
}
}
/**
* 订单项类,包含单个商品的购买信息
*/
class OrderItem {
private Product product; // 商品
private int quantity; // 数量
private double subtotal; // 小计
public OrderItem(Product product, int quantity) {
this.product = product;
this.quantity = quantity;
this.subtotal = product.getPrice() * quantity;
}
public double getSubtotal() {
return subtotal;
}
@Override
public String toString() {
return String.format(" - %s: 数量 %d, 单价 ¥%.2f, 小计 ¥%.2f",
product.getName(), quantity, product.getPrice(), subtotal);
}
}

View File

@@ -0,0 +1,67 @@
package com.inmind.s_test_044;
/**
* 商品类,存储商品信息
*/
public class Product {
private String id; // 商品ID
private String name; // 商品名称
private double price; // 商品价格
private String category; // 商品类别
private int stock; // 库存数量
public Product(String id, String name, double price, String category, int stock) {
this.id = id;
this.name = name;
this.price = price;
this.category = category;
this.stock = stock;
}
// 减少库存
public void reduceStock(int quantity) {
if (quantity <= stock) {
stock -= quantity;
}
}
// getter方法
public String getId() {
return id;
}
public String getName() {
return name;
}
public double getPrice() {
return price;
}
public String getCategory() {
return category;
}
public int getStock() {
return stock;
}
@Override
public String toString() {
return String.format("ID: %s, 名称: %s, 价格: ¥%.2f, 库存: %d",
id, name, price, stock);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Product product = (Product) o;
return id.equals(product.id);
}
@Override
public int hashCode() {
return id.hashCode();
}
}

View File

@@ -0,0 +1,323 @@
package com.inmind.s_test_044;
import java.util.*;
/**
* 购物系统主类,将购物车功能整合到主菜单
*/
public class ShoppingSystem {
// 使用List存储所有商品展示单列集合的应用
private static List<Product> products = new ArrayList<>();
// 使用Set存储所有用户确保用户唯一性
private static Set<User> users = new HashSet<>();
private static Scanner scanner = new Scanner(System.in);
private static User currentUser = null;
// 购物车使用Map存储商品和数量展示双列集合应用
private static Map<Product, Integer> shoppingCart = new HashMap<>();
public static void main(String[] args) {
// 初始化数据
initData();
System.out.println("===== 欢迎使用在线购物系统 =====");
// 用户登录
login();
if (currentUser != null) {
System.out.println("登录成功!欢迎您," + currentUser.getUsername() + "");
// 显示主菜单(包含购物车功能)
showMainMenu();
}
}
// 初始化商品和用户数据
private static void initData() {
// 添加商品
products.add(new Product("P001", "笔记本电脑", 5999.99, "电子产品", 10));
products.add(new Product("P002", "机械键盘", 299.99, "电脑配件", 20));
products.add(new Product("P003", "无线鼠标", 129.99, "电脑配件", 30));
products.add(new Product("P004", "蓝牙耳机", 799.99, "音频设备", 15));
products.add(new Product("P005", "智能手机", 3999.99, "电子产品", 25));
// 添加用户
users.add(new User("U001", "张三", "zhangsan@example.com"));
users.add(new User("U002", "李四", "lisi@example.com"));
users.add(new User("U003", "王五", "wangwu@example.com"));
}
// 用户登录
private static void login() {
System.out.print("请输入用户名: ");
String username = scanner.nextLine();
// 在Set集合中查找用户
for (User user : users) {
if (user.getUsername().equals(username)) {
currentUser = user;
return;
}
}
System.out.println("用户不存在,登录失败!");
}
// 显示主菜单(包含购物车功能)
private static void showMainMenu() {
while (true) {
System.out.println("\n===== 主菜单 =====");
System.out.println("1. 浏览商品");
System.out.println("2. 搜索商品");
System.out.println("3. 查看购物车");
System.out.println("4. 添加商品到购物车");
System.out.println("5. 修改购物车商品数量");
System.out.println("6. 从购物车删除商品");
System.out.println("7. 清空购物车");
System.out.println("8. 生成订单");
System.out.println("9. 退出系统");
System.out.print("请选择操作: ");
int choice;
try {
choice = Integer.parseInt(scanner.nextLine());
} catch (NumberFormatException e) {
System.out.println("请输入有效的数字");
continue;
}
switch (choice) {
case 1:
browseProducts();
break;
case 2:
searchProducts();
break;
case 3:
viewShoppingCart();
break;
case 4:
addToCart();
break;
case 5:
updateCartItemQuantity();
break;
case 6:
removeFromCart();
break;
case 7:
clearCart();
break;
case 8:
createOrder();
break;
case 9:
System.out.println("感谢使用,再见!");
scanner.close();
return;
default:
System.out.println("无效的选择,请重试");
}
}
}
// 浏览商品
private static void browseProducts() {
System.out.println("\n===== 所有商品 =====");
// 使用Map对商品进行分类展示
Map<String, List<Product>> productsByCategory = new HashMap<>();
for (Product product : products) {
String category = product.getCategory();
// 如果分类不存在,则创建新的列表
if (!productsByCategory.containsKey(category)) {
productsByCategory.put(category, new ArrayList<>());
}
productsByCategory.get(category).add(product);
}
// 遍历分类并显示商品
for (Map.Entry<String, List<Product>> entry : productsByCategory.entrySet()) {
System.out.println("\n【" + entry.getKey() + "");
for (Product product : entry.getValue()) {
System.out.println(product);
}
}
}
// 搜索商品
private static void searchProducts() {
System.out.print("请输入商品名称关键字: ");
String keyword = scanner.nextLine();
List<Product> result = new ArrayList<>();
for (Product product : products) {
if (product.getName().contains(keyword)) {
result.add(product);
}
}
System.out.println("\n===== 搜索结果 =====");
if (result.isEmpty()) {
System.out.println("没有找到匹配的商品");
} else {
for (Product product : result) {
System.out.println(product);
}
}
}
// 查看购物车
private static void viewShoppingCart() {
System.out.println("\n===== 我的购物车 =====");
if (shoppingCart.isEmpty()) {
System.out.println("购物车是空的");
return;
}
double total = 0;
for (Map.Entry<Product, Integer> entry : shoppingCart.entrySet()) {
Product product = entry.getKey();
int quantity = entry.getValue();
double subtotal = product.getPrice() * quantity;
total += subtotal;
System.out.printf("%s - 数量: %d, 单价: ¥%.2f, 小计: ¥%.2f%n",
product.getName(), quantity, product.getPrice(), subtotal);
}
System.out.printf("\n购物车总计: ¥%.2f%n", total);
}
// 添加商品到购物车
private static void addToCart() {
System.out.print("请输入要添加的商品ID: ");
String productId = scanner.nextLine();
for (Product product : products) {
if (product.getId().equals(productId)) {
System.out.print("请输入购买数量: ");
try {
int quantity = Integer.parseInt(scanner.nextLine());
if (quantity <= 0) {
System.out.println("数量必须大于0");
return;
}
// 检查库存
if (quantity > product.getStock()) {
System.out.println("库存不足,当前库存: " + product.getStock());
return;
}
// 添加到购物车
if (shoppingCart.containsKey(product)) {
shoppingCart.put(product, shoppingCart.get(product) + quantity);
} else {
shoppingCart.put(product, quantity);
}
System.out.println("已添加到购物车: " + product.getName() + ", 数量: " + quantity);
return;
} catch (NumberFormatException e) {
System.out.println("数量输入无效");
return;
}
}
}
System.out.println("未找到该商品ID");
}
// 更新购物车中商品的数量
private static void updateCartItemQuantity() {
System.out.print("请输入要修改数量的商品ID: ");
String productId = scanner.nextLine();
for (Product product : products) {
if (product.getId().equals(productId)) {
if (!shoppingCart.containsKey(product)) {
System.out.println("购物车中没有该商品");
return;
}
System.out.print("请输入新的数量: ");
try {
int quantity = Integer.parseInt(scanner.nextLine());
if (quantity <= 0) {
System.out.println("数量必须大于0");
return;
}
// 检查库存
if (quantity > product.getStock()) {
System.out.println("库存不足,当前库存: " + product.getStock());
return;
}
shoppingCart.put(product, quantity);
System.out.println("已更新数量: " + product.getName() + ", 新数量: " + quantity);
return;
} catch (NumberFormatException e) {
System.out.println("数量输入无效");
return;
}
}
}
System.out.println("未找到该商品ID");
}
// 从购物车中删除商品
private static void removeFromCart() {
System.out.print("请输入要删除的商品ID: ");
String productId = scanner.nextLine();
for (Product product : products) {
if (product.getId().equals(productId)) {
if (shoppingCart.containsKey(product)) {
shoppingCart.remove(product);
System.out.println("已从购物车中删除: " + product.getName());
} else {
System.out.println("购物车中没有该商品");
}
return;
}
}
System.out.println("未找到该商品ID");
}
// 清空购物车
private static void clearCart() {
shoppingCart.clear();
System.out.println("购物车已清空");
}
// 创建订单
private static void createOrder() {
if (shoppingCart.isEmpty()) {
System.out.println("购物车是空的,无法创建订单");
return;
}
System.out.println("正在创建订单...");
String orderId = "O" + System.currentTimeMillis();
Order order = new Order(orderId, currentUser);
// 将购物车中的商品添加到订单
for (Map.Entry<Product, Integer> entry : shoppingCart.entrySet()) {
Product product = entry.getKey();
int quantity = entry.getValue();
order.addOrderItem(product, quantity);
// 减少库存
product.reduceStock(quantity);
}
// 显示订单信息
order.displayOrder();
System.out.println("订单创建成功!");
// 清空购物车
shoppingCart.clear();
}
}

View File

@@ -0,0 +1,42 @@
package com.inmind.s_test_044;
/**
* 用户类,存储用户信息
*/
public class User {
private String id; // 用户ID
private String username; // 用户名
private String email; // 邮箱
public User(String id, String username, String email) {
this.id = id;
this.username = username;
this.email = email;
}
// getter方法
public String getId() {
return id;
}
public String getUsername() {
return username;
}
public String getEmail() {
return email;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
User user = (User) o;
return username.equals(user.username);
}
@Override
public int hashCode() {
return username.hashCode();
}
}

View File

@@ -0,0 +1,48 @@
package com.inmind.s_test_05;
// 账户类
class Account {
String id; // 账户ID
String name; // 账户名
double balance; // 余额
int pwdErrors; // 密码错误次数
boolean locked; // 是否锁定
static final int MAX_PWD_ERROR = 3; // 最大密码错误次数
static final String PWD = "123456"; // 默认密码
// 构造方法
public Account(String id, String name, double balance) {
this.id = id;
this.name = name;
this.balance = balance;
this.pwdErrors = 0;
this.locked = false;
}
// 存款
public void saveMoney(double amount) throws InvalidAmountException, AccountLockedException {
if (locked) throw new AccountLockedException("账户" + id + "已锁定");
if (amount <= 0) throw new InvalidAmountException("存款金额必须大于0");
balance += amount;
System.out.println(name + "存款" + amount + "元,当前余额:" + balance);
}
// 取款
public void getMoney(double amount, String pwd) throws Exception {
if (locked) throw new AccountLockedException("账户" + id + "已锁定");
// 密码验证
if (!PWD.equals(pwd)) {
pwdErrors++;
System.out.println("pwdErrors的值" + pwdErrors);
if (pwdErrors >= MAX_PWD_ERROR) {
locked = true;
throw new AccountLockedException("密码错误3次账户" + id + "已锁定");
}
throw new Exception("密码错误,剩余次数:" + (MAX_PWD_ERROR - pwdErrors));
}
if (amount <= 0) throw new InvalidAmountException("取款金额必须大于0");
if (amount > balance) throw new InsufficientFundsException("余额不足,当前余额:" + balance);
balance -= amount;
System.out.println(name + "取款" + amount + "元,当前余额:" + balance);
}
}

View File

@@ -0,0 +1,8 @@
package com.inmind.s_test_05;
// 自定义异常3账户锁定异常
class AccountLockedException extends Exception {
public AccountLockedException(String msg) {
super(msg);
}
}

View File

@@ -0,0 +1,45 @@
package com.inmind.s_test_05;
// 银行类
class Bank {
private Account[] accounts; // 账户数组
private int count; // 账户数量
private static final double MAX_TRANSFER = 50000; // 单笔最大转账额
// 构造方法
public Bank(int size) {
accounts = new Account[size];
count = 0;
}
// 创建账户
public void addAccount(Account acc) {
if (count < accounts.length) {
accounts[count++] = acc;
System.out.println("创建账户成功:" + acc.id + "(" + acc.name + ")");
}
}
// 查找账户
public Account findAccount(String id) throws Exception {
for (int i = 0; i < count; i++) {
if (accounts[i].id.equals(id)) {
return accounts[i];
}
}
throw new Exception("账户" + id + "不存在");
}
// 转账
public void transferMoney(String fromId, String toId, double amount, String pwd) throws Exception {
Account from = findAccount(fromId);
Account to = findAccount(toId);
if (amount <= 0) throw new InvalidAmountException("转账金额必须大于0");
if (amount > MAX_TRANSFER) throw new TransferLimitException("超过最大转账额" + MAX_TRANSFER);
from.getMoney(amount, pwd); // 先取款
to.saveMoney(amount); // 再存款
System.out.println("" + from.name + "" + to.name + "转账" + amount + "元成功");
}
}

View File

@@ -0,0 +1,8 @@
package com.inmind.s_test_05;
// 自定义异常1余额不足异常
class InsufficientFundsException extends Exception {
public InsufficientFundsException(String msg) {
super(msg);
}
}

View File

@@ -0,0 +1,8 @@
package com.inmind.s_test_05;
// 自定义异常2无效金额异常
class InvalidAmountException extends Exception {
public InvalidAmountException(String msg) {
super(msg);
}
}

View File

@@ -0,0 +1,65 @@
package com.inmind.s_test_05;
import java.util.Objects;
// 主程序
public class Test {
public static void main(String[] args) {
Bank bank = new Bank(10);
try {
// 创建账户
bank.addAccount(new Account("1001", "张三", 10000));
bank.addAccount(new Account("1002", "李四", 5000));
Account zhang = bank.findAccount("1001");
// 正常操作
zhang.saveMoney(2000);
zhang.getMoney(3000, "123456");
// 测试异常场景
try {
zhang.getMoney(20000, "123456");
} // 余额不足
catch (InsufficientFundsException e) {
System.out.println("异常:" + e.getMessage());
}
try {
bank.transferMoney("1001", "1002", 60000, "123456");
} // 转账超限
catch (TransferLimitException e) {
System.out.println("异常:" + e.getMessage());
}
try {
zhang.getMoney(1000, "111");
} // 密码错误
catch (Exception e) {
System.out.println("异常:" + e.getMessage());
}
try {
zhang.getMoney(1000, "111");
} // 锁定账户
catch (Exception e) {
System.out.println("异常:" + e.getMessage());
}
try {
zhang.getMoney(1000, "111");
} // 锁定账户
catch (AccountLockedException e) {
System.out.println("异常:" + e.getMessage());
}
try {
zhang.getMoney(1000, "111");
} // 锁定账户
catch (AccountLockedException e) {
System.out.println("异常:" + e.getMessage());
}
} catch (Exception e) {
System.out.println("系统错误:" + e.getMessage());
}
}
}

View File

@@ -0,0 +1,8 @@
package com.inmind.s_test_05;
// 自定义异常4转账超限异常
class TransferLimitException extends Exception {
public TransferLimitException(String msg) {
super(msg);
}
}

View File

@@ -0,0 +1,10 @@
package com.inmind.s_test_06;
import java.util.concurrent.Callable;
public class MyCallable implements Callable<String> {
@Override
public String call() throws Exception {
return "";
}
}

View File

@@ -0,0 +1,14 @@
package com.inmind.s_test_06;
public class MyRunnable implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"执行了任务");
try {
Thread.sleep(14000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}

View File

@@ -0,0 +1,160 @@
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
// 银行账户类,包含两种同步方式的操作方法
class BankAccount {
private int balance; // 账户余额
private Lock lock; // 显式锁对象,用于同步控制
// 构造方法:初始化账户余额和锁对象
public BankAccount(int initialBalance) {
this.balance = initialBalance; // 设置初始余额
this.lock = new ReentrantLock(); // 初始化可重入锁
}
// 1. 使用synchronized关键字实现存款操作自动同步
public synchronized void depositWithSync(int amount) {
// 只处理正数存款
if (amount > 0) {
// 计算新余额
int newBalance = balance + amount;
// 模拟银行处理时间100毫秒
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace(); // 处理中断异常
}
// 更新余额
balance = newBalance;
// 打印操作信息:当前线程名、存款金额、最新余额
System.out.println(Thread.currentThread().getName() +
" 存款 " + amount + ",余额: " + balance);
}
}
// 2. 使用Lock实现取款操作手动同步
public void withdrawWithLock(int amount) {
lock.lock(); // 手动获取锁,确保操作安全
try {
// 检查取款金额是否有效(正数且不超过余额)
if (amount > 0 && amount <= balance) {
// 计算新余额
int newBalance = balance - amount;
// 模拟银行处理时间100毫秒
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace(); // 处理中断异常
}
// 更新余额
balance = newBalance;
// 打印操作信息
System.out.println(Thread.currentThread().getName() +
" 取款 " + amount + ",余额: " + balance);
} else {
// 取款失败提示
System.out.println(Thread.currentThread().getName() +
" 取款失败,余额不足");
}
} finally {
lock.unlock(); // 确保锁一定会被释放,避免死锁
}
}
// 获取当前账户余额
public int getBalance() {
return balance;
}
}
// 存款任务类实现Runnable接口封装存款操作
class DepositTask implements Runnable {
private BankAccount account; // 目标银行账户
private int amount; // 存款金额
// 构造方法:指定操作的账户和金额
public DepositTask(BankAccount account, int amount) {
this.account = account;
this.amount = amount;
}
// 线程执行的任务:调用同步存款方法
@Override
public void run() {
account.depositWithSync(amount);
}
}
// 取款任务类实现Runnable接口封装取款操作
class WithdrawTask implements Runnable {
private BankAccount account; // 目标银行账户
private int amount; // 取款金额
// 构造方法:指定操作的账户和金额
public WithdrawTask(BankAccount account, int amount) {
this.account = account;
this.amount = amount;
}
// 线程执行的任务调用Lock取款方法
@Override
public void run() {
account.withdrawWithLock(amount);
}
}
// 主类:演示多线程操作银行账户
public class Test {
public static void main(String[] args) {
// 创建一个初始余额为1000的银行账户
BankAccount account = new BankAccount(1000);
// 第一部分演示Thread和Runnable的基本使用
System.out.println("=== 演示Thread和Runnable ===");
// 创建存款线程:线程名"存款人A"存款500
Thread depositThread1 = new Thread(
new DepositTask(account, 500), "存款人A");
// 创建取款线程:线程名"取款人X"取款300
Thread withdrawThread1 = new Thread(
new WithdrawTask(account, 300), "取款人X");
// 启动两个线程
depositThread1.start();
withdrawThread1.start();
// 等待两个线程执行完成后再继续
try {
depositThread1.join(); // 主线程等待存款线程完成
withdrawThread1.join(); // 主线程等待取款线程完成
} catch (InterruptedException e) {
e.printStackTrace();
}
// 第二部分演示线程池Executors的使用
System.out.println("\n=== 演示线程池Executors ===");
// 创建固定大小为3的线程池
ExecutorService executor = Executors.newFixedThreadPool(3);
// 向线程池提交多个任务
executor.submit(new DepositTask(account, 200)); // 存款人B存200
executor.submit(new WithdrawTask(account, 400)); // 取款人Y取400
executor.submit(new DepositTask(account, 1000)); // 存款人C存1000
executor.submit(new WithdrawTask(account, 600)); // 取款人Z取600
// 关闭线程池(不再接受新任务,等待现有任务完成)
executor.shutdown();
}
}

View File

@@ -0,0 +1,44 @@
package com.inmind.s_test_06;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class ThreadPoolTest1 {
public static void main(String[] args) {
/*
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler)
*/
//AbortPolicy就是一个拒绝策略新任务来了无法处理就抛出异常
ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(3, 5, 8,
TimeUnit.SECONDS, new ArrayBlockingQueue<>(4), Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy());
//如何将任务交给线程池
MyRunnable task = new MyRunnable();
poolExecutor.execute(task);//线程池会自动创建一个新线程,自动处理这个任务
poolExecutor.execute(task);//线程池会自动创建一个新线程,自动处理这个任务
poolExecutor.execute(task);//线程池会自动创建一个新线程,自动处理这个任务
//线程任务时间加长之后3个线程占用4个任务队列排满就开始创建新的临时线程
poolExecutor.execute(task);//复用前面核心线程
poolExecutor.execute(task);//复用前面核心线程
poolExecutor.execute(task);
poolExecutor.execute(task);
//到了临时线程创建时机
poolExecutor.execute(task);
poolExecutor.execute(task);
//再来新的任务,就到了拒绝新任务的处理
poolExecutor.execute(task);
poolExecutor.shutdown();//等待线程池任务结束后才关闭线程池
poolExecutor.shutdownNow();//不等待线程池任务结束,立即关闭线程池
}
}

View File

@@ -0,0 +1,14 @@
package com.inmind.s_test_06;
import java.util.concurrent.*;
public class ThreadPoolTest2 {
public static void main(String[] args) {
ExecutorService poolExecutor = new ThreadPoolExecutor(3, 5, 8,
TimeUnit.SECONDS, new ArrayBlockingQueue<>(4), Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy());
//如何将任务交给线程池
}
}

View File

@@ -0,0 +1,142 @@
package com.inmind.s_test_07;
/*
需求说明
本案例模拟学生成绩管理系统,需要实现以下业务功能:
生成测试学生数据(包含姓名、年龄、成绩)
打印所有学生的完整信息
筛选并打印成绩及格≥60 分)的学生
统计 18 岁以上且成绩及格的学生数量
提取并打印所有学生的姓名
将学生成绩转换为等级A/B/C/D并展示
获取并展示第 3-5 名学生信息(按原始顺序)
合并 "及格学生" 和 "前 2 名学生" 两个数据集并展示
技术点说明
Supplier 接口:用于提供学生数据列表,体现 "供给型" 功能
Consumer 接口:用于消费学生对象(打印信息),体现 "消费型" 功能
Predicate 接口:用于定义筛选条件(成绩及格、成年),体现 "判断型" 功能包含条件组合and
Function 接口:用于数据转换(学生→姓名、成绩→等级),体现 "功能型" 功能
Stream 方法:
forEach遍历元素
filter按条件筛选
count统计元素数量
map元素转换
skip跳过指定数量元素
limit限制获取元素数量
concat合并两个流
通过这个案例可以清晰看到 lambda 表达式如何与四大核心函数式接口配合,以及 Stream API 的各种方法在实际业务中的应用,所有操作都围绕真实业务场景设计,便于理解 lambda 表达式的实用价值
*/
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.stream.Stream;
// 学生类
class Student {
private String name;
private int age;
private double score;
public Student(String name, int age, double score) {
this.name = name;
this.age = age;
this.score = score;
}
// getter方法
public String getName() { return name; }
public int getAge() { return age; }
public double getScore() { return score; }
@Override
public String toString() {
return "姓名: " + name + ", 年龄: " + age + ", 成绩: " + score;
}
}
public class StudentScorePractice {
public static void main(String[] args) {
// 1. 使用Supplier接口生成测试数据提供学生列表
Supplier<List<Student>> studentSupplier = () -> {
List<Student> students = new ArrayList<>();
students.add(new Student("张三", 18, 85.5));
students.add(new Student("李四", 17, 92.0));
students.add(new Student("王五", 19, 68.5));
students.add(new Student("赵六", 16, 59.0));
students.add(new Student("钱七", 20, 76.5));
students.add(new Student("孙八", 18, 95.0));
students.add(new Student("周九", 17, 45.5));
students.add(new Student("吴十", 19, 88.0));
return students;
};
// 获取学生列表
List<Student> students = studentSupplier.get();
// 2. 使用Consumer接口打印学生信息消费学生数据
Consumer<Student> printStudent = (s) -> System.out.println(s);
// 3. 使用Consumer遍历所有学生
System.out.println("=== 所有学生信息 ===");
students.stream().forEach(printStudent);
// 4. 使用Predicate定义筛选条件成绩及格>=60
Predicate<Student> isPass = (s) -> s.getScore() >= 60;
// 5. 使用filter+Predicate筛选及格学生并打印
System.out.println("\n=== 及格学生信息 ===");
students.stream()
.filter(isPass)
.forEach(printStudent);
// 6. 统计18岁以上及格学生数量count用法
Predicate<Student> isAdult = (s) -> s.getAge() >= 18;
long adultPassCount = students.stream()
.filter(isPass.and(isAdult)) // Predicate组合
.count();
System.out.println("\n18岁以上及格学生数量: " + adultPassCount);
// 7. 使用Function将学生转换为姓名数据转换
Function<Student, String> toName = (s) -> s.getName();
// 8. 使用map+Function获取所有学生姓名并打印
System.out.println("\n=== 所有学生姓名 ===");
students.stream()
.map(toName)
.forEach(name -> System.out.println(name));
// 9. 使用Function将学生成绩转换为等级A:90+, B:80-89, C:60-79, D:60-
Function<Student, String> scoreToLevel = (s) -> {
double score = s.getScore();
if (score >= 90) return "A";
else if (score >= 80) return "B";
else if (score >= 60) return "C";
else return "D";
};
// 10. 转换并打印学生成绩等级
System.out.println("\n=== 学生成绩等级 ===");
students.stream()
.map(scoreToLevel)
.forEach(level -> System.out.println(level));
// 11. 使用skip和limit获取中间范围数据跳过前2个取3个
System.out.println("\n=== 第3-5名学生按原始顺序 ===");
students.stream()
.skip(2) // 跳过前2个
.limit(3) // 取3个
.forEach(printStudent);
// 12. 使用concat合并两个流及格学生流 + 前2名学生流
Stream<Student> passStream = students.stream().filter(isPass);
Stream<Student> top2Stream = students.stream().limit(2);
System.out.println("\n=== 合并流(及格学生 + 前2名学生 ===");
Stream.concat(passStream, top2Stream)
.forEach(printStudent);
}
}

View File

@@ -0,0 +1,236 @@
package com.inmind.s_test_08;
import java.io.File;
import java.io.FilenameFilter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Scanner;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class CompactFileManager {
private static Scanner scanner = new Scanner(System.in);
private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
private static String currentPath = System.getProperty("user.home");
public static void main(String[] args) {
while (true) {
System.out.println("\n===== 文件管理工具 =====");
System.out.println("当前路径: " + currentPath);
System.out.println("1. 浏览目录 2. 切换目录 3. 创建文件/目录");
System.out.println("4. 删除项目 5. 搜索文件 6. 批量操作 7. 退出");
System.out.print("请选择: ");
int choice;
try {
choice = Integer.parseInt(scanner.nextLine());
if (choice < 1 || choice > 7) {
System.out.println("请输入1-7之间的数字!");
continue;
}
} catch (NumberFormatException e) {
System.out.println("请输入有效数字!");
continue;
}
switch (choice) {
case 1: browseDirectory(); break;
case 2: changeDirectory(); break;
case 3: createItem(); break;
case 4: deleteItem(); break;
case 5: searchFiles(); break;
case 6: batchOperations(); break;
case 7:
System.out.println("再见!");
scanner.close();
return;
}
}
}
// 浏览当前目录
private static void browseDirectory() {
File dir = new File(currentPath);
if (!dir.exists() || !dir.isDirectory()) {
System.out.println("无效目录!");
return;
}
File[] items = dir.listFiles();
if (items == null || items.length == 0) {
System.out.println("目录为空");
return;
}
System.out.println("\n目录内容:");
System.out.printf("%-5s %-30s %-15s %s%n", "类型", "名称", "大小", "修改时间");
System.out.println("------------------------------------------------");
// 先显示目录,再显示文件
for (File item : items) {
if (item.isDirectory()) {
printItemInfo(item);
}
}
for (File item : items) {
if (item.isFile()) {
printItemInfo(item);
}
}
}
// 打印项目信息
private static void printItemInfo(File item) {
String type = item.isDirectory() ? "目录" : "文件";
String size = item.isDirectory() ? "-" : item.length() + "B";
String time = sdf.format(new Date(item.lastModified()));
System.out.printf("%-5s %-30s %-15s %s%n", type, item.getName(), size, time);
}
// 切换目录
private static void changeDirectory() {
System.out.print("输入目标路径(..返回上一级): ");
String path = scanner.nextLine().trim();
File newDir = path.equals("..") ? new File(currentPath).getParentFile() :
new File(path).isAbsolute() ? new File(path) :
new File(currentPath + File.separator + path);
if (newDir != null && newDir.exists() && newDir.isDirectory()) {
currentPath = newDir.getAbsolutePath();
System.out.println("已切换到: " + currentPath);
} else {
System.out.println("目录不存在!");
}
}
// 创建文件或目录
private static void createItem() {
System.out.print("1.创建文件 2.创建目录,请选择: ");
String type = scanner.nextLine().trim();
System.out.print("请输入名称: ");
String name = scanner.nextLine().trim();
if (name.isEmpty()) {
System.out.println("名称不能为空!");
return;
}
File item = new File(currentPath + File.separator + name);
if (item.exists()) {
System.out.println("已存在同名项目!");
return;
}
try {
boolean success = "1".equals(type) ? item.createNewFile() : item.mkdirs();
System.out.println(success ? "创建成功!" : "创建失败!");
} catch (Exception e) {
System.out.println("创建失败: " + e.getMessage());
}
}
// 删除项目
private static void deleteItem() {
System.out.print("输入要删除的名称: ");
String name = scanner.nextLine().trim();
File item = new File(currentPath + File.separator + name);
if (!item.exists()) {
System.out.println("项目不存在!");
return;
}
System.out.print("确定删除? (y/n): ");
if ("y".equals(scanner.nextLine().trim().toLowerCase())) {
boolean success = deleteRecursive(item);
System.out.println(success ? "删除成功!" : "删除失败!");
} else {
System.out.println("已取消");
}
}
// 递归删除
private static boolean deleteRecursive(File item) {
if (item.isDirectory()) {
File[] children = item.listFiles();
if (children != null) {
for (File child : children) {
if (!deleteRecursive(child)) return false;
}
}
}
return item.delete();
}
// 搜索文件
private static void searchFiles() {
System.out.print("输入搜索关键词: ");
String keyword = scanner.nextLine().trim().toLowerCase();
System.out.print("1.当前目录 2.包含子目录,请选择: ");
int scope = Integer.parseInt(scanner.nextLine().trim());
List<File> results = new ArrayList<>();
if (scope == 1) {
File[] items = new File(currentPath).listFiles();
if (items != null) {
for (File item : items) {
if (item.getName().toLowerCase().contains(keyword)) {
results.add(item);
}
}
}
} else {
searchRecursive(new File(currentPath), keyword, results);
}
System.out.println("找到 " + results.size() + " 个匹配项:");
results.forEach(f -> System.out.println((f.isDirectory() ? "[目录] " : "[文件] ") + f.getAbsolutePath()));
}
// 递归搜索
private static void searchRecursive(File dir, String keyword, List<File> results) {
if (!dir.isDirectory()) return;
File[] items = dir.listFiles();
if (items == null) return;
for (File item : items) {
if (item.getName().toLowerCase().contains(keyword)) results.add(item);
if (item.isDirectory()) searchRecursive(item, keyword, results);
}
}
// 批量操作
private static void batchOperations() {
System.out.print("输入文件扩展名(如txt): ");
String ext = scanner.nextLine().trim().toLowerCase();
if (ext.isEmpty()) {
System.out.println("扩展名不能为空!");
return;
}
// 使用过滤器筛选特定类型文件
File dir = new File(currentPath);
File[] files = dir.listFiles(new FilenameFilter() {
@Override
public boolean accept(File d, String name) {
return new File(d, name).isFile() && name.toLowerCase().endsWith("." + ext);
}
});
if (files == null || files.length == 0) {
System.out.println("未找到." + ext + "文件");
return;
}
System.out.println("找到 " + files.length + " 个文件:");
Stream.of(files).forEach(f -> System.out.println(" " + f.getName()));
System.out.print("是否删除这些文件? (y/n): ");
if ("y".equals(scanner.nextLine().trim().toLowerCase())) {
long count = java.util.Arrays.stream(files).filter(f -> f.delete()).count();
System.out.println("已删除 " + count + " 个文件");
}
}
}

View File

@@ -0,0 +1,302 @@
package com.inmind.s_test_08;
import java.io.File;
import java.io.FilenameFilter;
import java.text.SimpleDateFormat;
import java.util.*;
// 文件管理工具类,实现基本的文件和目录操作
public class FileManagerWithComments {
// 用于接收用户输入的扫描器
private static Scanner scanner = new Scanner(System.in);
// 用于格式化文件修改时间的日期格式化器
private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
// 当前工作目录,初始化为用户主目录
private static String currentPath = System.getProperty("user.home");
// 主方法,程序入口
public static void main(String[] args) {
// 循环显示主菜单,直到用户选择退出
while (true) {
System.out.println("\n===== 文件管理工具 =====");
System.out.println("当前路径: " + currentPath);
System.out.println("1. 浏览目录 2. 切换目录 3. 创建文件/目录");
System.out.println("4. 删除项目 5. 搜索文件 6. 批量操作 7. 退出");
System.out.print("请选择: ");
int choice;
try {
// 读取用户选择
choice = Integer.parseInt(scanner.nextLine());
// 验证选择是否在有效范围内
if (choice < 1 || choice > 7) {
System.out.println("请输入1-7之间的数字!");
continue;
}
} catch (NumberFormatException e) {
// 处理非数字输入的异常
System.out.println("请输入有效数字!");
continue;
}
// 根据用户选择执行相应操作
switch (choice) {
case 1: browseDirectory(); break;
case 2: changeDirectory(); break;
case 3: createItem(); break;
case 4: deleteItem(); break;
case 5: searchFiles(); break;
case 6: batchOperations(); break;
case 7:
System.out.println("再见!");
scanner.close();
return;
}
}
}
// 浏览当前目录内容
private static void browseDirectory() {
// 创建当前目录的File对象
File dir = new File(currentPath);
// 检查目录是否有效
if (!dir.exists() || !dir.isDirectory()) {
System.out.println("无效目录!");
return;
}
// 获取目录下的所有文件和子目录
File[] items = dir.listFiles();
// 检查目录是否为空
if (items == null || items.length == 0) {
System.out.println("目录为空");
return;
}
// 显示目录内容标题
System.out.println("\n目录内容:");
System.out.println("类型 名称 大小 修改时间");
System.out.println("------------------------------------------------");
// 先显示所有子目录
for (File item : items) {
if (item.isDirectory()) {
printItemInfo(item);
}
}
// 再显示所有文件
for (File item : items) {
if (item.isFile()) {
printItemInfo(item);
}
}
}
// 打印文件或目录的详细信息
private static void printItemInfo(File item) {
// 确定项目类型(目录或文件)
String type = item.isDirectory() ? "目录" : "文件";
// 确定大小信息(目录无大小,文件显示字节数)
String size = item.isDirectory() ? "-" : item.length() + "B";
// 格式化修改时间
String time = sdf.format(new Date(item.lastModified()));
// 拼接并打印信息,保持列对齐
String line = padRight(type, 6) + padRight(item.getName(), 30) +
padRight(size, 15) + time;
System.out.println(line);
}
// 辅助方法:将字符串右对齐并填充空格至指定长度
private static String padRight(String str, int length) {
// 如果字符串过长,截断并加空格
if (str.length() >= length) {
return str.substring(0, length - 1) + " ";
}
// 否则补空格至指定长度
StringBuilder sb = new StringBuilder(str);
while (sb.length() < length) {
sb.append(" ");
}
return sb.toString();
}
// 切换当前工作目录
private static void changeDirectory() {
System.out.print("输入目标路径(..返回上一级): ");
String path = scanner.nextLine().trim();
// 处理返回上一级、绝对路径和相对路径三种情况
File newDir = path.equals("..") ? new File(currentPath).getParentFile() :
new File(path).isAbsolute() ? new File(path) :
new File(currentPath + File.separator + path);
// 验证目录是否有效并切换
if (newDir != null && newDir.exists() && newDir.isDirectory()) {
currentPath = newDir.getAbsolutePath();
System.out.println("已切换到: " + currentPath);
} else {
System.out.println("目录不存在!");
}
}
// 创建文件或目录
private static void createItem() {
System.out.print("1.创建文件 2.创建目录,请选择: ");
String type = scanner.nextLine().trim();
System.out.print("请输入名称: ");
String name = scanner.nextLine().trim();
// 验证名称不为空
if (name.isEmpty()) {
System.out.println("名称不能为空!");
return;
}
// 创建对应的File对象
File item = new File(currentPath + File.separator + name);
// 检查是否已存在同名项目
if (item.exists()) {
System.out.println("已存在同名项目!");
return;
}
try {
// 根据选择创建文件或目录
boolean success = "1".equals(type) ? item.createNewFile() : item.mkdirs();
System.out.println(success ? "创建成功!" : "创建失败!");
} catch (Exception e) {
System.out.println("创建失败: " + e.getMessage());
}
}
// 删除文件或目录
private static void deleteItem() {
System.out.print("输入要删除的名称: ");
String name = scanner.nextLine().trim();
// 创建对应的File对象
File item = new File(currentPath + File.separator + name);
// 检查项目是否存在
if (!item.exists()) {
System.out.println("项目不存在!");
return;
}
// 确认删除操作
System.out.print("确定删除? (y/n): ");
if ("y".equals(scanner.nextLine().trim().toLowerCase())) {
// 执行删除操作
boolean success = deleteRecursive(item);
System.out.println(success ? "删除成功!" : "删除失败!");
} else {
System.out.println("已取消");
}
}
// 递归删除目录(先删除子内容,再删除自身)
private static boolean deleteRecursive(File item) {
// 如果是目录,先删除所有子文件和子目录
if (item.isDirectory()) {
File[] children = item.listFiles();
if (children != null) {
for (File child : children) {
// 递归删除子项,若有一项失败则整体失败
if (!deleteRecursive(child)) return false;
}
}
}
// 删除当前项目(文件或空目录)
return item.delete();
}
// 搜索文件或目录
private static void searchFiles() {
System.out.print("输入搜索关键词: ");
String keyword = scanner.nextLine().trim().toLowerCase();
System.out.print("1.当前目录 2.包含子目录,请选择: ");
int scope = Integer.parseInt(scanner.nextLine().trim());
// 存储搜索结果的列表
List<File> results = new ArrayList<>();
// 仅在当前目录搜索
if (scope == 1) {
File[] items = new File(currentPath).listFiles();
if (items != null) {
for (File item : items) {
// 检查名称是否包含关键词
if (item.getName().toLowerCase().contains(keyword)) {
results.add(item);
}
}
}
} else {
// 递归搜索所有子目录
searchRecursive(new File(currentPath), keyword, results);
}
// 显示搜索结果
System.out.println("找到 " + results.size() + " 个匹配项:");
results.forEach(f -> {
System.out.println((f.isDirectory() ? "[目录] " : "[文件] ") + f.getAbsolutePath());
});
}
// 递归搜索文件
private static void searchRecursive(File dir, String keyword, List<File> results) {
// 如果不是目录,直接返回
if (!dir.isDirectory()) return;
// 获取目录下的所有项目
File[] items = dir.listFiles();
if (items == null) return;
// 遍历所有项目
for (File item : items) {
// 如果名称包含关键词,加入结果列表
if (item.getName().toLowerCase().contains(keyword)) results.add(item);
// 如果是目录,递归搜索其子目录
if (item.isDirectory()) searchRecursive(item, keyword, results);
}
}
// 批量操作(筛选并删除特定类型文件)
private static void batchOperations() {
System.out.print("输入文件扩展名(如txt): ");
String ext = scanner.nextLine().trim().toLowerCase();
// 验证扩展名不为空
if (ext.isEmpty()) {
System.out.println("扩展名不能为空!");
return;
}
// 使用文件过滤器筛选特定类型的文件
File dir = new File(currentPath);
File[] files = dir.listFiles(new FilenameFilter() {
@Override
public boolean accept(File d, String name) {
// 筛选条件:是文件且扩展名匹配
return new File(d, name).isFile() && name.toLowerCase().endsWith("." + ext);
}
});
// 检查是否找到匹配文件
if (files == null || files.length == 0) {
System.out.println("未找到." + ext + "文件");
return;
}
// 显示找到的文件
System.out.println("找到 " + files.length + " 个文件:");
for (File f : files) {
System.out.println(" " + f.getName());
}
// 确认并执行批量删除
System.out.print("是否删除这些文件? (y/n): ");
if ("y".equals(scanner.nextLine().trim().toLowerCase())) {
int count = 0;
for (File f : files) {
if (f.delete()) count++;
}
System.out.println("已删除 " + count + " 个文件");
}
}
}

View File

@@ -0,0 +1,18 @@
package com.inmind.s_test_08;
import java.io.*;
import java.nio.charset.Charset;
import java.util.Properties;
public class PropertiesDemo {
public static void main(String[] args) throws IOException {
Properties prop = new Properties();
InputStream fis = new FileInputStream("demo.properties");
InputStreamReader isr = new InputStreamReader(fis,"UTF-8");
FileReader fr = new FileReader("demo.properties", Charset.forName("UTF-8"));
prop.load(fr);
fis.close();
isr.close();
System.out.println(prop);
}
}

View File

@@ -0,0 +1,41 @@
package com.inmind.s_test_11;
import java.net.*;
import java.util.Scanner;
/*
目标完成UDP通信快速入门实现1发1收
*/
public class UdpDemo {
public static void main(String[] args) throws Exception {
//1.创建客户端对象(发韭菜出去的人)
DatagramSocket socket = new DatagramSocket();
//2.创建数据包对象封装要发出去的数据(创建一个韭菜盘子)
/*
public DatagramPacket(byte buf[], int offset, int length,
InetAddress address, int port)
参数一:封装要发出去的数据
参数二:发送出去的数据大小(字节个数)
参数三服务端的IP地址找到服务器主机
参数四:服务端程序的端口号
*/
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("请输入:");
String msg = sc.nextLine();
if ("exit".equals(msg)) {
System.out.println("谢谢使用,退出成功!!");
socket.close();
break;
}
byte[] bytes = msg.getBytes();
DatagramPacket packet = new DatagramPacket(bytes, bytes.length, InetAddress.getLocalHost(),10022);
//3.开始正式发送这个数据包的数据出去
socket.send(packet);
}
}
}

View File

@@ -0,0 +1,30 @@
package com.inmind.s_test_11;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
public class UpdServerDemo {
public static void main(String[] args) throws Exception {
System.out.println("-------服务端启动了------");
//1.创建服务端对象
DatagramSocket socket = new DatagramSocket(10022);
byte[] buffer = new byte[1024 * 64];
while (true) {
//2.创建一个数据包对象,用于接收数据的(创建韭菜盘子)
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
//3.开始正式使用数据包来接收客户端发来的数据
socket.receive(packet);
//4.从字节数组中,把接收到的数据直接打印出来
//接收多少就打印多少
int length = packet.getLength();
String result = new String(buffer, 0, length);
System.out.println(result);
System.out.println(packet.getAddress().getHostAddress());
System.out.println(packet.getPort());
}
// socket.close();
}
}

View File

@@ -0,0 +1,35 @@
package com.inmind.s_test_11;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class WebServerDemo {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(10088);
while (true) {
Socket socket = serverSocket.accept();
System.out.println("接收到一个请求");
//将工程中已有的index.html文件的数据响应给浏览器
OutputStream out = socket.getOutputStream();
// 因为请求是一个浏览器使用到了http协议所以要遵循http协议的规范。
//写回去的前三行固定, 前两行是一些字符, 第三行必须是空行
out.write("HTTP/1.1 200 OK\r\n".getBytes());// 第一行
out.write("Content-Type:text/html\r\n\r\n".getBytes());//第二行 第三行(空行)
//边读边输出网页字节数据
FileInputStream fis = new FileInputStream("index.html");
byte[] bytes = new byte[1024];
int len;
while ((len = fis.read(bytes))!=-1) {
out.write(bytes,0,len);
}
fis.close();
socket.close();
}
// serverSocket.close();
}
}

View File

@@ -0,0 +1,87 @@
package com.inmind.s_test_11.chatroom.client;
import java.io.*;
import java.net.Socket;
import java.util.Scanner;
public class Client {
public static void main(String[] args) throws IOException {
Socket socket = new Socket("127.0.0.1", 10001);
System.out.println("服务器已经连接成功");
while (true) {
System.out.println("==============欢迎来到黑马聊天室================");
System.out.println("1登录");
System.out.println("2注册");
System.out.println("请输入您的选择:");
Scanner sc = new Scanner(System.in);
String choose = sc.nextLine();
switch (choose) {
case "1" : login(socket); break;
case "2" : System.out.println("用户选择了注册"); break;
default : System.out.println("没有这个选项");
}
}
}
public static void login(Socket socket) throws IOException {
//获取输出流
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
//键盘录入
Scanner sc = new Scanner(System.in);
System.out.println("请输入用户名");
String username = sc.nextLine();
System.out.println("请输入密码");
String password = sc.nextLine();
//拼接
StringBuilder sb = new StringBuilder();
//username=zhangsan&password=123
sb.append("username=").append(username).append("&password=").append(password);
//第一次写的是执行登录操作
bw.write("login");
bw.newLine();
bw.flush();
//第二次写的是用户名和密码的信息
//往服务器写出用户名和密码
bw.write(sb.toString());
bw.newLine();
bw.flush();
//接收数据
//获取输入流
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String message = br.readLine();
System.out.println(message);
//1登录成功 2 密码有误 3 用户名不存在
if ("1".equals(message)) {
System.out.println("登录成功,开始聊天");
//开一条单独的线程,专门用来接收服务端发送过来的聊天记录
new Thread(new ClientMyRunnable(socket)).start();
//开始聊天
talk2All(bw);
} else if ("2".equals(message)) {
System.out.println("密码输入错误");
} else if ("3".equals(message)) {
System.out.println("用户名不存在");
}
}
//往服务器写出消息
private static void talk2All(BufferedWriter bw) throws IOException {
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("请输入您要说的话");
String str = sc.nextLine();
//把聊天内容写给服务器
bw.write(str);
bw.newLine();
bw.flush();
}
}
}

View File

@@ -0,0 +1,29 @@
package com.inmind.s_test_11.chatroom.client;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
class ClientMyRunnable implements Runnable{
Socket socket;
public ClientMyRunnable(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
//循环,重复的接受
while (true) {
try {
//接收服务器发送过来的聊天记录
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String msg = br.readLine();
System.out.println(msg);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

View File

@@ -0,0 +1,94 @@
package com.inmind.s_test_11.chatroom.server;
import java.io.*;
import java.net.Socket;
import java.util.Properties;
class MyRunnable implements Runnable {
Socket socket;
Properties prop;
public MyRunnable(Socket socket, Properties prop) {
this.prop = prop;
this.socket = socket;
}
@Override
public void run() {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while (true) {
String choose = br.readLine();
switch (choose) {
case "login" : login(br);break;
case "register" : System.out.println("用户选择了注册操作");break;
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
//获取用户登录时,传递过来的信息。
//并进行判断
public void login(BufferedReader br) throws IOException {
System.out.println("用户选择了登录操作");
String userinfo = br.readLine();
//username=zhangsan&password=123
String[] userInfoArr = userinfo.split("&");
String usernameInput = userInfoArr[0].split("=")[1];
String passwordInput = userInfoArr[1].split("=")[1];
System.out.println("用户输入的用户名为:" + usernameInput);
System.out.println("用户输入的密码为:" + passwordInput);
if (prop.containsKey(usernameInput)) {
//如果用户名存在,继续判断密码
String rightPassword = prop.get(usernameInput) + "";
if (rightPassword.equals(passwordInput)) {
//提示用户登录成功,可以开始聊天
writeMessage2Client("1");
//登录成功的时候就需要把客户端的连接对象Socket保存起来
Server.list.add(socket);
//写一个while(){}表示正在聊天
//接收客户端发送过来的消息,并打印在控制台
talk2All(br, usernameInput);
} else {
//密码输入有误
writeMessage2Client("2");
}
} else {
//如果用户名不存在,直接回写
writeMessage2Client("3");
}
}
private void talk2All(BufferedReader br, String username) throws IOException {
while (true) {
String message = br.readLine();
System.out.println(username + "发送过来消息:" + message);
//群发
for (Socket s : Server.list) {
//s依次表示每一个客户端的连接对象
writeMessage2Client(s, username + "发送过来消息:" + message);
}
}
}
public void writeMessage2Client(String message) throws IOException {
//获取输出流
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
bw.write(message);
bw.newLine();
bw.flush();
}
public void writeMessage2Client(Socket s, String message) throws IOException {
//获取输出流
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
bw.write(message);
bw.newLine();
bw.flush();
}
}

View File

@@ -0,0 +1,32 @@
package com.inmind.s_test_11.chatroom.server;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Properties;
public class Server {
static ArrayList<Socket> list = new ArrayList<>();
public static void main(String[] args) throws IOException {
ServerSocket ss = new ServerSocket(10001);
//1.把本地文件中正确的用户名和密码获取到
Properties prop = new Properties();
// FileInputStream fis = new FileInputStream("sockethomework\\servicedir\\userinfo.txt");
FileInputStream fis = new FileInputStream("day01\\src\\com\\inmind\\s_test_11\\chatroom\\userinfo.txt");
prop.load(fis);
fis.close();
//2.只要来了一个客户端,就开一条线程处理
while (true) {
Socket socket = ss.accept();
System.out.println("有客户端来链接");
new Thread(new MyRunnable(socket, prop)).start();
}
}
}

View File

@@ -0,0 +1,3 @@
zhangsan=123
lisi=1234
wangwu=12345

View File

@@ -0,0 +1,101 @@
package com.inmind.s_test_11.chatroom1;
import java.io.*;
import java.net.*;
public class ChatClient {
private String serverAddress; // 服务器地址
private int serverPort; // 服务器端口
private String username; // 客户端用户名
// 构造方法,初始化服务器地址、端口和用户名
public ChatClient(String serverAddress, int serverPort, String username) {
this.serverAddress = serverAddress;
this.serverPort = serverPort;
this.username = username;
}
// 启动客户端
public void start() {
try (Socket socket = new Socket(serverAddress, serverPort)) {
// 初始化输入流,用于读取服务器发送的消息
BufferedReader in = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
// 初始化输出流用于向服务器发送消息autoFlush设为true
PrintWriter out = new PrintWriter(
socket.getOutputStream(), true);
// 发送用户名到服务器
out.println(username);
// 启动接收消息的线程
new Thread(new ReceiveHandler(in)).start();
// 读取控制台输入的流
BufferedReader consoleIn = new BufferedReader(
new InputStreamReader(System.in));
String input;
// 循环读取控制台输入并发送给服务器
while ((input = consoleIn.readLine()) != null) {
out.println(input);
// 如果输入"exit",则退出聊天
if (input.equalsIgnoreCase("exit")) {
break;
}
}
} catch (IOException e) {
System.err.println("客户端错误: " + e.getMessage());
}
}
// 接收消息的线程类,负责读取服务器发送的消息
private class ReceiveHandler implements Runnable {
private BufferedReader in; // 从服务器读取消息的输入流
public ReceiveHandler(BufferedReader in) {
this.in = in;
}
public void run() {
try {
String message;
// 循环读取服务器发送的消息并打印到控制台
while ((message = in.readLine()) != null) {
System.out.println(message);
}
} catch (IOException e) {
System.err.println("接收消息错误: " + e.getMessage());
}
}
}
// 客户端主方法
public static void main(String[] args) {
// 默认连接本地服务器
String serverAddress = "localhost";
int serverPort = 12345;
// 获取用户输入的用户名
BufferedReader consoleIn = new BufferedReader(
new InputStreamReader(System.in));
System.out.print("请输入您的用户名: ");
try {
String username = consoleIn.readLine();
// 如果用户未输入用户名,使用默认匿名用户
if (username == null || username.trim().isEmpty()) {
username = "匿名用户";
}
System.out.println("连接到服务器...");
// 创建并启动客户端
ChatClient client = new ChatClient(serverAddress, serverPort, username);
System.out.println("连接成功输入消息开始聊天输入exit退出。");
client.start();
} catch (IOException e) {
System.err.println("无法获取用户名: " + e.getMessage());
}
}
}

View File

@@ -0,0 +1,111 @@
package com.inmind.s_test_11.chatroom1;
import java.io.*;
import java.net.*;
import java.util.*;
import java.io.*;
import java.net.*;
import java.util.*;
public class ChatServer {
// 服务器监听的端口号
private static final int PORT = 12345;
// 存储所有客户端输出流的集合,用于广播消息
private static Set<PrintWriter> clientWriters = new HashSet<>();
public static void main(String[] args) {
System.out.println("多人聊天服务器启动,监听端口: " + PORT);
try (ServerSocket serverSocket = new ServerSocket(PORT)) {
// 循环接受客户端连接
while (true) {
// 阻塞等待客户端连接
Socket clientSocket = serverSocket.accept();
System.out.println("新客户端连接: " + clientSocket);
// 创建PrintWriter用于向客户端发送消息
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
// 将新客户端的输出流添加到集合中,使用同步块确保线程安全
synchronized (clientWriters) {
clientWriters.add(out);
}
// 为每个客户端创建并启动一个新的处理线程
new Thread(new ClientHandler(clientSocket, out)).start();
}
} catch (IOException e) {
System.err.println("服务器错误: " + e.getMessage());
}
}
// 客户端处理线程类,负责接收客户端消息并广播
private static class ClientHandler implements Runnable {
private Socket clientSocket; // 客户端Socket
private PrintWriter out; // 向客户端输出的流
private String username; // 客户端用户名
public ClientHandler(Socket socket, PrintWriter out) {
this.clientSocket = socket;
this.out = out;
}
public void run() {
try {
// 读取客户端发送的数据
BufferedReader in = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
// 读取客户端发送的用户名
username = in.readLine();
System.out.println("用户 " + username + " 加入聊天");
// 广播新用户加入的消息
broadcast(username + " 加入了聊天!");
// 循环读取客户端发送的消息
String input;
while ((input = in.readLine()) != null) {
// 如果用户输入exit退出循环
if (input.equalsIgnoreCase("exit")) {
break;
}
// 广播用户发送的消息
broadcast(username + ": " + input);
}
// 用户退出时的处理
System.out.println("用户 " + username + " 离开聊天");
broadcast(username + " 离开了聊天!");
} catch (IOException e) {
System.err.println("与客户端通信错误: " + e.getMessage());
} finally {
// 清理资源
if (out != null) {
// 从客户端集合中移除当前客户端的输出流
synchronized (clientWriters) {
clientWriters.remove(out);
}
}
try {
// 关闭客户端连接
clientSocket.close();
} catch (IOException e) {
System.err.println("关闭客户端连接错误: " + e.getMessage());
}
}
}
// 广播消息给所有连接的客户端
private void broadcast(String message) {
// 同步遍历客户端输出流集合,确保线程安全
synchronized (clientWriters) {
for (PrintWriter writer : clientWriters) {
writer.println(message);
}
}
}
}
}

View File

@@ -0,0 +1,23 @@
package com.inmind.s_test_12;
//import org.junit.Test;
public class JunitDemo {
// @Test
public void method1() throws Exception {
int i = 1/1;
Class clazz = Class.forName("com.itheima.reflect_02.Student");
//clazz.newInstance():底层调用指定类的无参构造方式
Object o = clazz.newInstance();
System.out.println(o);
}
// @Test
public void method2(){
int[] arr = {1,2,3 };
System.out.println(arr);
}
}

View File

@@ -0,0 +1,225 @@
package com.inmind.s_test_12;
import java.lang.annotation.*;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
/*
业务说明
这个案例实现了一个通用对象验证框架,核心业务是对 Java 对象的字段进行自动化验证,适用于需要数据校验的场景(如表单提交、接口参数校验等)。
业务流程
定义验证规则:通过自定义注解(@NotNull、@Range、@Email标记需要验证的字段并设置验证条件如非空、数值范围、邮箱格式
标记待验证类:在需要验证的类上添加@Validatable注解声明该类需要进行字段验证。
执行验证调用Validator.validate()方法,传入待验证对象,框架会通过反射自动检查所有字段的注解并执行验证逻辑。
返回验证结果:验证结果包含 “是否通过” 和具体错误信息,方便后续处理(如提示用户修正数据)。
*/
// 枚举:定义验证错误的类型,用于分类错误信息
enum ValidationErrorType {
NOT_NULL, // 非空错误字段值为null时触发
MIN_VALUE, // 最小值错误:数值小于允许的最小值时触发
MAX_VALUE, // 最大值错误:数值大于允许的最大值时触发
INVALID_EMAIL // 邮箱格式错误:邮箱地址格式不正确时触发
}
// 枚举:定义验证器的类型,用于标识不同的验证规则
enum ValidatorType {
NOT_NULL, // 非空验证器
RANGE, // 范围验证器
EMAIL // 邮箱验证器
}
// 注解:类级注解,标记该类需要进行字段验证
@Target(ElementType.TYPE) // 注解适用范围:类、接口等
@Retention(RetentionPolicy.RUNTIME) // 注解保留策略:运行时可通过反射获取
@interface Validatable {
}
// 注解字段级注解标记字段不允许为null
@Target(ElementType.FIELD) // 注解适用范围:成员变量
@Retention(RetentionPolicy.RUNTIME) // 运行时可访问
@interface NotNull {
String message() default "字段不能为null"; // 错误提示信息,有默认值
}
// 注解:字段级注解,标记字段值需要在指定范围内(适用于数值类型)
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface Range {
int min() default 0; // 最小值默认0
int max() default Integer.MAX_VALUE; // 最大值,默认整数最大值
String message() default "字段值超出范围"; // 错误提示信息
}
// 注解:字段级注解,标记字段需要验证邮箱格式
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface Email {
String message() default "邮箱格式不正确"; // 错误提示信息
}
// 验证结果类:封装验证的结果信息
class ValidationResult {
private boolean valid; // 验证是否通过
private List<String> errorMessages = new ArrayList<>(); // 错误信息列表
// 获取验证是否通过的状态
public boolean isValid() {
return valid;
}
// 设置验证状态
public void setValid(boolean valid) {
this.valid = valid;
}
// 获取错误信息列表
public List<String> getErrorMessages() {
return errorMessages;
}
// 添加错误信息
public void addErrorMessage(String message) {
errorMessages.add(message);
}
}
// 验证器工具类:核心类,使用反射执行验证逻辑
class Validator {
// 验证对象的公共方法,返回验证结果
public static ValidationResult validate(Object obj) {
ValidationResult result = new ValidationResult();
result.setValid(true); // 默认验证通过
// 检查对象所属的类是否标记了@Validatable注解未标记则直接返回
if (!obj.getClass().isAnnotationPresent(Validatable.class)) {
return result;
}
try {
// 通过反射获取类的所有字段(包括私有字段)
Field[] fields = obj.getClass().getDeclaredFields();
// 遍历每个字段进行验证
for (Field field : fields) {
// 设置私有字段可访问(否则无法获取值)
field.setAccessible(true);
String fieldName = field.getName(); // 获取字段名
Object value = field.get(obj); // 获取字段的值
// 验证@NotNull注解如果字段标记了该注解且值为null则添加错误
if (field.isAnnotationPresent(NotNull.class) && value == null) {
NotNull annotation = field.getAnnotation(NotNull.class); // 获取注解实例
result.addErrorMessage(fieldName + ": " + annotation.message()); // 添加错误信息
result.setValid(false); // 标记验证失败
}
// 验证@Range注解仅对数值类型且值不为null的字段生效
if (field.isAnnotationPresent(Range.class) && value != null) {
// 检查字段值是否为数字类型
if (value instanceof Number) {
Range annotation = field.getAnnotation(Range.class); // 获取注解实例
Number number = (Number) value; // 转换为数字类型
// 检查是否小于最小值
if (number.intValue() < annotation.min()) {
result.addErrorMessage(fieldName + ": " + annotation.message() +
"(最小值: " + annotation.min() + ")");
result.setValid(false);
}
// 检查是否大于最大值
if (number.intValue() > annotation.max()) {
result.addErrorMessage(fieldName + ": " + annotation.message() +
"(最大值: " + annotation.max() + ")");
result.setValid(false);
}
}
}
// 验证@Email注解仅对字符串类型且值不为null的字段生效
if (field.isAnnotationPresent(Email.class) && value != null) {
// 检查字段值是否为字符串类型
if (value instanceof String) {
Email annotation = field.getAnnotation(Email.class); // 获取注解实例
String email = (String) value; // 转换为字符串
// 简单验证邮箱格式(包含@符号)
if (!email.contains("@")) {
result.addErrorMessage(fieldName + ": " + annotation.message());
result.setValid(false);
}
}
}
}
} catch (IllegalAccessException e) {
// 处理反射访问异常
e.printStackTrace();
result.setValid(false);
result.addErrorMessage("验证过程中发生错误: " + e.getMessage());
}
return result;
}
}
// 示例实体类:用户信息类,标记了@Validatable表示需要验证
@Validatable
class User {
@NotNull(message = "用户名不能为空") // 用户名不允许为null
private String username;
@Range(min = 18, max = 120, message = "年龄必须在18到120之间") // 年龄范围限制
private int age;
@Email(message = "请输入有效的邮箱地址") // 邮箱格式验证
private String email;
// 构造方法:初始化用户信息
public User(String username, int age, String email) {
this.username = username;
this.age = age;
this.email = email;
}
// getter和setter方法用于访问和修改字段值
public String getUsername() { return username; }
public void setUsername(String username) { this.username = username; }
public int getAge() { return age; }
public void setAge(int age) { this.age = age; }
public String getEmail() { return email; }
public void setEmail(String email) { this.email = email; }
}
// 主类:程序入口,演示验证功能
public class ValidationDemo {
public static void main(String[] args) {
// 创建两个测试用户对象
User validUser = new User("张三", 25, "zhangsan@example.com"); // 符合所有验证规则
User invalidUser = new User(null, 15, "invalid-email"); // 不符合验证规则
// 验证有效用户
System.out.println("验证有效用户:");
ValidationResult validResult = Validator.validate(validUser);
printValidationResult(validResult);
// 验证无效用户
System.out.println("\n验证无效用户:");
ValidationResult invalidResult = Validator.validate(invalidUser);
printValidationResult(invalidResult);
}
// 打印验证结果的工具方法
private static void printValidationResult(ValidationResult result) {
if (result.isValid()) {
System.out.println("验证通过!");
} else {
System.out.println("验证失败,错误信息:");
for (String message : result.getErrorMessages()) {
System.out.println("- " + message);
}
}
}
}

View File

@@ -0,0 +1,300 @@
package com.inmind.s_test_12_2;
import java.lang.annotation.*;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
/*
业务说明
这个案例实现了一个通用对象验证框架,核心业务是对 Java 对象的字段进行自动化验证,适用于需要数据校验的场景(如表单提交、接口参数校验等)。
业务流程
定义验证规则:通过自定义注解(@NotNull、@Range、@Email标记需要验证的字段并设置验证条件如非空、数值范围、邮箱格式
标记待验证类:在需要验证的类上添加@Validatable注解声明该类需要进行字段验证。
执行验证调用Validator.validate()方法,传入待验证对象,框架会通过反射自动检查所有字段的注解并执行验证逻辑。
返回验证结果:验证结果包含 “是否通过” 和具体错误信息,方便后续处理(如提示用户修正数据)。
错误类型:使用枚举定义错误类型
*/
// 枚举:定义验证错误的类型,用于分类错误信息
enum ValidationErrorType {
NOT_NULL, // 非空错误字段值为null时触发
MIN_VALUE, // 最小值错误:数值小于允许的最小值时触发
MAX_VALUE, // 最大值错误:数值大于允许的最大值时触发
INVALID_EMAIL // 邮箱格式错误:邮箱地址格式不正确时触发
}
// 枚举:定义验证器的类型,用于标识不同的验证规则
enum ValidatorType {
NOT_NULL, // 非空验证器
RANGE, // 范围验证器
EMAIL // 邮箱验证器
}
// 验证错误信息类:包含错误类型和错误描述
class ValidationError {
private ValidationErrorType errorType; // 错误类型
private String message; // 错误描述
public ValidationError(ValidationErrorType errorType, String message) {
this.errorType = errorType;
this.message = message;
}
public ValidationErrorType getErrorType() {
return errorType;
}
public String getMessage() {
return message;
}
@Override
public String toString() {
return "[" + errorType + "] " + message;
}
}
// 注解:类级注解,标记该类需要进行字段验证
@Target(ElementType.TYPE) // 注解适用范围:类、接口等
@Retention(RetentionPolicy.RUNTIME) // 注解保留策略:运行时可通过反射获取
@interface Validatable {
}
// 注解字段级注解标记字段不允许为null
@Target(ElementType.FIELD) // 注解适用范围:成员变量
@Retention(RetentionPolicy.RUNTIME) // 运行时可访问
@interface NotNull {
String message() default "字段不能为null"; // 错误提示信息,有默认值
ValidatorType type() default ValidatorType.NOT_NULL; // 关联的验证器类型
}
// 注解:字段级注解,标记字段值需要在指定范围内(适用于数值类型)
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface Range {
int min() default 0; // 最小值默认0
int max() default Integer.MAX_VALUE; // 最大值,默认整数最大值
String message() default "字段值超出范围"; // 错误提示信息
ValidatorType type() default ValidatorType.RANGE; // 关联的验证器类型
}
// 注解:字段级注解,标记字段需要验证邮箱格式
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface Email {
String message() default "邮箱格式不正确"; // 错误提示信息
ValidatorType type() default ValidatorType.EMAIL; // 关联的验证器类型
}
// 验证结果类:封装验证的结果信息
class ValidationResult {
private boolean valid; // 验证是否通过
private List<ValidationError> errors = new ArrayList<>(); // 错误列表
// 获取验证是否通过的状态
public boolean isValid() {
return valid;
}
// 设置验证状态
public void setValid(boolean valid) {
this.valid = valid;
}
// 获取错误列表
public List<ValidationError> getErrors() {
return errors;
}
// 添加错误信息
public void addError(ValidationError error) {
errors.add(error);
}
// 根据错误类型筛选错误
public List<ValidationError> getErrorsByType(ValidationErrorType type) {
List<ValidationError> result = new ArrayList<>();
for (ValidationError error : errors) {
if (error.getErrorType() == type) {
result.add(error);
}
}
return result;
}
}
// 验证器工具类:核心类,使用反射执行验证逻辑
class Validator {
// 验证对象的公共方法,返回验证结果
public static ValidationResult validate(Object obj) {
ValidationResult result = new ValidationResult();
result.setValid(true); // 默认验证通过
// 检查对象所属的类是否标记了@Validatable注解未标记则直接返回
if (!obj.getClass().isAnnotationPresent(Validatable.class)) {
return result;
}
try {
// 通过反射获取类的所有字段(包括私有字段)
Field[] fields = obj.getClass().getDeclaredFields();
// 遍历每个字段进行验证
for (Field field : fields) {
// 设置私有字段可访问(否则无法获取值)
field.setAccessible(true);
String fieldName = field.getName(); // 获取字段名
Object value = field.get(obj); // 获取字段的值
// 验证@NotNull注解如果字段标记了该注解且值为null则添加错误
if (field.isAnnotationPresent(NotNull.class)) {
// 演示ValidatorType的使用获取注解关联的验证器类型
ValidatorType validatorType = field.getAnnotation(NotNull.class).type();
System.out.println("对字段[" + fieldName + "]使用" + validatorType + "进行验证");
if (value == null) {
NotNull annotation = field.getAnnotation(NotNull.class);
// 使用ValidationErrorType创建错误信息
result.addError(new ValidationError(
ValidationErrorType.NOT_NULL,
fieldName + ": " + annotation.message()
));
result.setValid(false);
}
}
// 验证@Range注解仅对数值类型且值不为null的字段生效
if (field.isAnnotationPresent(Range.class) && value != null) {
// 演示ValidatorType的使用
ValidatorType validatorType = field.getAnnotation(Range.class).type();
System.out.println("对字段[" + fieldName + "]使用" + validatorType + "进行验证");
// 检查字段值是否为数字类型
if (value instanceof Number) {
Range annotation = field.getAnnotation(Range.class);
Number number = (Number) value;
// 检查是否小于最小值
if (number.intValue() < annotation.min()) {
result.addError(new ValidationError(
ValidationErrorType.MIN_VALUE,
fieldName + ": " + annotation.message() + "(最小值: " + annotation.min() + ")"
));
result.setValid(false);
}
// 检查是否大于最大值
if (number.intValue() > annotation.max()) {
result.addError(new ValidationError(
ValidationErrorType.MAX_VALUE,
fieldName + ": " + annotation.message() + "(最大值: " + annotation.max() + ")"
));
result.setValid(false);
}
}
}
// 验证@Email注解仅对字符串类型且值不为null的字段生效
if (field.isAnnotationPresent(Email.class) && value != null) {
// 演示ValidatorType的使用
ValidatorType validatorType = field.getAnnotation(Email.class).type();
System.out.println("对字段[" + fieldName + "]使用" + validatorType + "进行验证");
// 检查字段值是否为字符串类型
if (value instanceof String) {
Email annotation = field.getAnnotation(Email.class);
String email = (String) value;
// 简单验证邮箱格式(包含@符号)
if (!email.contains("@")) {
result.addError(new ValidationError(
ValidationErrorType.INVALID_EMAIL,
fieldName + ": " + annotation.message()
));
result.setValid(false);
}
}
}
}
} catch (IllegalAccessException e) {
// 处理反射访问异常
e.printStackTrace();
result.setValid(false);
result.addError(new ValidationError(
null, "验证过程中发生错误: " + e.getMessage()
));
}
return result;
}
}
// 示例实体类:用户信息类,标记了@Validatable表示需要验证
@Validatable
class User {
@NotNull(message = "用户名不能为空") // 用户名不允许为null
private String username;
@Range(min = 18, max = 120, message = "年龄必须在18到120之间") // 年龄范围限制
private int age;
@Email(message = "请输入有效的邮箱地址") // 邮箱格式验证
private String email;
// 构造方法:初始化用户信息
public User(String username, int age, String email) {
this.username = username;
this.age = age;
this.email = email;
}
// getter和setter方法
public String getUsername() { return username; }
public void setUsername(String username) { this.username = username; }
public int getAge() { return age; }
public void setAge(int age) { this.age = age; }
public String getEmail() { return email; }
public void setEmail(String email) { this.email = email; }
}
// 主类:程序入口,演示验证功能
public class ValidationDemo1 {
public static void main(String[] args) {
// 创建两个测试用户对象
User validUser = new User("张三", 25, "zhangsan@example.com"); // 符合所有验证规则
User invalidUser = new User(null, 15, "invalid-email"); // 不符合验证规则
// 验证有效用户
System.out.println("=== 验证有效用户 ===");
ValidationResult validResult = Validator.validate(validUser);
printValidationResult(validResult);
// 验证无效用户
System.out.println("\n=== 验证无效用户 ===");
ValidationResult invalidResult = Validator.validate(invalidUser);
printValidationResult(invalidResult);
// 演示根据错误类型筛选错误
System.out.println("\n=== 按错误类型筛选结果 ===");
List<ValidationError> notNullErrors = invalidResult.getErrorsByType(ValidationErrorType.NOT_NULL);
System.out.println("非空错误数量: " + notNullErrors.size());
for (ValidationError error : notNullErrors) {
System.out.println(error);
}
}
// 打印验证结果的工具方法
private static void printValidationResult(ValidationResult result) {
if (result.isValid()) {
System.out.println("验证通过!");
} else {
System.out.println("验证失败,错误信息:");
for (ValidationError error : result.getErrors()) {
System.out.println("- " + error);
}
}
}
}

View File

@@ -0,0 +1,42 @@
package com.inmind.s_test_13;
import java.io.Serializable;
public class Log implements Serializable {
private static final long serialVersionUID = 2330914830532482231L;
private long timestamp;
private String level;
private String module;
private String content;
public Log(long timestamp, String level, String module, String content) {
this.timestamp = timestamp;
this.level = level;
this.module = module;
this.content = content;
}
// getter方法
public long getTimestamp() {
return timestamp;
}
public String getLevel() {
return level;
}
public String getModule() {
return module;
}
public String getContent() {
return content;
}
@Override
public String toString() {
return "[" + timestamp + "] " + level + " " + module + ": " + content;
}
}

View File

@@ -0,0 +1,235 @@
package com.inmind.s_test_13;
import java.io.*;
import java.net.ConnectException;
import java.net.Socket;
import java.util.*;
import java.util.stream.Collectors;
/**
* 日志分析器主类不使用Stream分组统计改用Map手动统计
*/
public class LogAnalyzer {
// 日志文件目录
private static final String LOG_DIR = "D:\\io_test";
// 服务器地址和端口
private static final String SERVER_HOST = "localhost";
private static final int SERVER_PORT = 8080;
// 日志列表非线程安全全集合通过synchronized保证安全
private List<Log> logs = new ArrayList<>();
public static void main(String[] args) {
LogAnalyzer analyzer = new LogAnalyzer();
try {
// 1. 多线程读取和解析日志文件
analyzer.readAndParseLogs();
// 2. 分析统计日志使用Map手动统计
Map<String, Integer> levelCountMap = analyzer.countByLevel();
Map<String, Integer> errorModuleMap = analyzer.countErrorByModule();
List<Log> earliestLogs = analyzer.getEarliestLogs(3);
// 3. 上报统计结果
analyzer.reportToServer(levelCountMap, errorModuleMap, earliestLogs);
System.out.println("日志分析和上报完成");
} catch (Exception e) {
System.err.println("日志分析过程中发生错误: " + e.getMessage());
e.printStackTrace();
}
}
/**
* 多线程读取和解析日志文件(使用普通线程)
*/
public void readAndParseLogs() throws IOException, InterruptedException {
// 检查日志目录是否存在
File logDir = new File(LOG_DIR);
if (!logDir.exists() || !logDir.isDirectory()) {
throw new FileNotFoundException("日志目录不存在: " + LOG_DIR);
}
// 获取所有.log文件
File[] logFiles = logDir.listFiles((dir, name) -> name.endsWith(".log"));
if (logFiles == null || logFiles.length == 0) {
System.out.println("没有找到日志文件");
return;
}
System.out.println("找到 " + logFiles.length + " 个日志文件,开始解析...");
// 创建线程列表
List<Thread> threads = new ArrayList<>();
// 为每个文件创建一个线程
for (File file : logFiles) {
Thread thread = new Thread(() -> parseLogFile(file));
threads.add(thread);
thread.start();
}
// 等待所有线程完成
for (Thread thread : threads) {
thread.join();
}
System.out.println("日志解析完成,共解析 " + logs.size() + " 条日志");
}
/**
* 解析单个日志文件
*/
private void parseLogFile(File file) {
try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
String line;
int lineNumber = 0;
while ((line = reader.readLine()) != null) {
lineNumber++;
try {
Log log = parseLogLine(line);
if (log != null) {
// 使用synchronized保证线程安全
synchronized (this) {
logs.add(log);
}
}
} catch (Exception e) {
System.err.println("解析文件 " + file.getName() + " 的第 " + lineNumber + " 行失败: " + e.getMessage());
System.err.println("错误行内容: " + line);
}
}
System.out.println("解析完成: " + file.getName() + ",共 " + (lineNumber - 1) + "");
} catch (IOException e) {
System.err.println("读取日志文件 " + file.getName() + " 失败: " + e.getMessage());
}
}
/**
* 解析单条日志(使用逗号分隔格式)
* 日志格式:时间戳,级别,模块,内容
* 例如1696123456789,ERROR,Payment,支付失败,订单号:ORDER123
*/
private Log parseLogLine(String line) {
// 去除首尾可能存在的空格
line = line.trim();
// 按逗号分割限制分割次数为4确保内容部分的逗号不被分割
String[] parts = line.split(",", 4);
// 验证格式是否正确
if (parts.length != 4) {
throw new IllegalArgumentException("日志格式错误需要4个字段实际得到" + parts.length + "");
}
// 提取各个字段
String timestampStr = parts[0];
String level = parts[1];
String module = parts[2];
String content = parts[3];
// 验证时间戳格式
try {
long timestamp = Long.parseLong(timestampStr);
return new Log(timestamp, level, module, content);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("时间戳格式错误: " + timestampStr);
}
}
/**
* 按级别统计日志数量使用Map手动统计
*/
public Map<String, Integer> countByLevel() {
Map<String, Integer> levelCountMap = new HashMap<>();
// 同步读取日志列表
synchronized (this) {
for (Log log : logs) {
String level = log.getLevel();
// 存在则加1不存在则设为1
if (levelCountMap.containsKey(level)) {
levelCountMap.put(level, levelCountMap.get(level) + 1);
} else {
levelCountMap.put(level, 1);
}
}
}
return levelCountMap;
}
/**
* 按模块统计错误日志数量使用Map手动统计
*/
public Map<String, Integer> countErrorByModule() {
Map<String, Integer> errorModuleMap = new HashMap<>();
// 同步读取日志列表
synchronized (this) {
for (Log log : logs) {
// 只统计ERROR级别的日志
if ("ERROR".equals(log.getLevel())) {
String module = log.getModule();
// 存在则加1不存在则设为1
if (errorModuleMap.containsKey(module)) {
errorModuleMap.put(module, errorModuleMap.get(module) + 1);
} else {
errorModuleMap.put(module, 1);
}
}
}
}
return errorModuleMap;
}
/**
* 获取最早的N条日志使用普通排序
*/
public List<Log> getEarliestLogs(int n) {
// 先创建副本再排序,避免影响原始列表
List<Log> sortedLogs;
synchronized (this) {
sortedLogs = new ArrayList<>(logs);
}
// 手动排序不使用Stream
sortedLogs.sort(new Comparator<Log>() {
@Override
public int compare(Log log1, Log log2) {
return Long.compare(log1.getTimestamp(), log2.getTimestamp());
}
});
// 取前N条
return sortedLogs.stream().limit(n).collect(Collectors.toList());
}
/**
* 向服务器上报统计结果
*/
public void reportToServer(Map<String, Integer> levelCountMap,
Map<String, Integer> errorModuleMap,
List<Log> earliestLogs) throws IOException, ClassNotFoundException {
try (Socket socket = new Socket(SERVER_HOST, SERVER_PORT);
ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
ObjectInputStream in = new ObjectInputStream(socket.getInputStream())) {
// 发送统计结果
out.writeObject(levelCountMap);
out.writeObject(errorModuleMap);
out.writeObject(earliestLogs);
out.flush();
// 接收响应
String response = (String) in.readObject();
System.out.println("服务器响应: " + response);
} catch (ConnectException e) {
throw new ConnectException("无法连接到服务器 " + SERVER_HOST + ":" + SERVER_PORT + ",请确保服务器已启动");
}
}
}

View File

@@ -0,0 +1,63 @@
package com.inmind.s_test_13;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.List;
import java.util.Map;
/**
* 日志分析服务器,接收客户端上报的统计结果
*/
public class LogServer {
private static final int PORT = 8080;
public static void main(String[] args) {
System.out.println("日志分析服务器启动,监听端口: " + PORT);
try (ServerSocket serverSocket = new ServerSocket(PORT)) {
while (true) {
// 等待客户端连接
try (Socket clientSocket = serverSocket.accept();
ObjectInputStream in = new ObjectInputStream(clientSocket.getInputStream());
ObjectOutputStream out = new ObjectOutputStream(clientSocket.getOutputStream())) {
System.out.println("客户端连接成功: " + clientSocket.getInetAddress());
// 接收统计结果
Map<String, Integer> levelCountMap = (Map<String, Integer>) in.readObject();
Map<String, Integer> errorModuleMap = (Map<String, Integer>) in.readObject();
List<Log> earliestLogs = (List<Log>) in.readObject();
// 打印统计结果
System.out.println("\n===== 日志统计结果 =====");
System.out.println("\n1. 按级别统计:");
for (Map.Entry<String, Integer> entry : levelCountMap.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue() + "");
}
System.out.println("\n2. 按模块错误统计:");
for (Map.Entry<String, Integer> entry : errorModuleMap.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue() + "条错误");
}
System.out.println("\n3. 最早的3条日志:");
for (Log log : earliestLogs) {
System.out.println(log);
}
// 发送响应
out.writeObject("上报成功");
out.flush();
} catch (Exception e) {
System.err.println("处理客户端请求出错: " + e.getMessage());
e.printStackTrace();
}
}
} catch (IOException e) {
System.err.println("服务器启动失败: " + e.getMessage());
e.printStackTrace();
}
}
}

View File

@@ -0,0 +1,19 @@
package com.inmind.s_test_13.proxy;
//歌手类
public class CaiXuKun implements Singer {
@Override
public void sing(int money) {
System.out.println("蔡徐坤收到了"+money+"钱,唱了鸡你太美");
}
@Override
public void dance(int money) {
System.out.println("蔡徐坤收到了"+money+"钱,跳了篮球舞");
}
@Override
public void eat() {
System.out.println("蔡徐坤吃了大盘鸡");
}
}

View File

@@ -0,0 +1,70 @@
package com.inmind.s_test_13.proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class ProxyDemo {
public static void main(String[] args) {
CaiXuKun caiXuKun = new CaiXuKun();
//动态地创建出代理对象,谈唱跳功能的价格
//参数一:类加载器对象
ClassLoader loader = caiXuKun.getClass().getClassLoader();
//参数二:代理对象要与被代理对象拥有相同的功能,Singer
Class<?>[] interfaces = caiXuKun.getClass().getInterfaces();
//参数三:处理器对象,用来处理代理对象中的业务逻辑
InvocationHandler h = new InvocationHandler() {
/*
注意:动态代理对象singerProxy调用任意的方法,都会引起,invoke方法执行一次
invoke方法的三个参数:
参数一proxy:动态代理对象singerProxy(不要使用,它引起递归,导致栈内存溢出错误)
参数二method:反射中Method类,就是当前动态代理调用的方法sing,dance...
参数三args:当前动态代理调用的方法传入的实参
*/
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//System.out.println("inovke方法执行了");
/*
动态代理增强的代码
1.如果是sing,那么要100万才让蔡徐坤唱
2.如果是dance,那么要200万才让蔡徐坤跳
*/
// if (method.getName().equals("sing")) {
if ("sing".equals(method.getName())) {
int money = (int) args[0];
if (money > 100) {
// caiXuKun.sing(money);
return method.invoke(caiXuKun, args);
} else {
System.out.println("钱不够,一边玩去");
}
return null;
}
if ("dance".equals(method.getName())) {
int money = (int) args[0];
if (money > 200) {
// caiXuKun.dance(money);
return method.invoke(caiXuKun, args);
} else {
System.out.println("钱不够,一边玩去");
}
return null;
}
//注意:我们此时针对sing,dance,进行了拦截,但是它还有其他的功能,如果不要拦截,那就得执行它原本的功能
return method.invoke(caiXuKun,args);
}
};
/*
创建了一个动态代理对象
注意:为了调用要拦截的sing,dance,此时的o对象必须强转成对应singer接口类型
*/
Singer singerProxy = (Singer) Proxy.newProxyInstance(loader, interfaces, h);
singerProxy.sing(150);
singerProxy.dance(150);
singerProxy.eat();
}
}

View File

@@ -0,0 +1,8 @@
package com.inmind.s_test_13.proxy;
//定义出一个歌手的规范,只要拥有该接口的方法,那么对应的类就算是一个歌手类
public interface Singer {
void sing(int money);
void dance(int money);
void eat();
}

View File

@@ -0,0 +1,89 @@
package com.inmind.test07;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
StudentManager manager = new StudentManager();
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("===== 学生管理系统 =====");
System.out.println("1. 添加学生");
System.out.println("2. 删除学生");
System.out.println("3. 修改学生信息");
System.out.println("4. 查找学生");
System.out.println("5. 显示所有学生");
System.out.println("6. 退出系统");
System.out.print("请输入你的选择:");
int choice = scanner.nextInt();
scanner.nextLine(); // 消耗换行符
switch (choice) {
case 1:
addStudent(scanner, manager);
break;
case 2:
deleteStudent(scanner, manager);
break;
case 3:
updateStudent(scanner, manager);
break;
case 4:
findStudent(scanner, manager);
break;
case 5:
manager.displayAllStudents();
break;
case 6:
System.out.println("感谢使用学生管理系统,再见!");
scanner.close();
return;
default:
System.out.println("无效的选择,请重新输入!");
}
}
}
private static void addStudent(Scanner scanner, StudentManager manager) {
System.out.println("=== 添加学生 ===");
System.out.print("请输入学生ID");
int id = scanner.nextInt();
scanner.nextLine(); // 消耗换行符
System.out.print("请输入学生姓名:");
String name = scanner.nextLine();
System.out.print("请输入学生年龄:");
int age = scanner.nextInt();
scanner.nextLine(); // 消耗换行符
System.out.print("请输入学生地址:");
String address = scanner.nextLine();
Student student = new Student(id, name, age, address);
manager.addStudent(student);
}
private static void deleteStudent(Scanner scanner, StudentManager manager) {
System.out.println("=== 删除学生 ===");
System.out.print("请输入要删除的学生ID");
int id = scanner.nextInt();
scanner.nextLine(); // 消耗换行符
manager.deleteStudent(id);
}
private static void updateStudent(Scanner scanner, StudentManager manager) {
System.out.println("=== 修改学生信息 ===");
System.out.print("请输入要修改的学生ID");
int id = scanner.nextInt();
scanner.nextLine(); // 消耗换行符
manager.updateStudent(id);
}
private static void findStudent(Scanner scanner, StudentManager manager) {
System.out.println("=== 查找学生 ===");
System.out.print("请输入要查找的学生ID");
int id = scanner.nextInt();
scanner.nextLine(); // 消耗换行符
manager.findStudent(id);
}
}

View File

@@ -0,0 +1,110 @@
package com.inmind.test07;
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
/*
数组 随机 scanner的抽奖案例
1.动态定义出参与获奖的人数和姓名
2.动态定义奖品内容
3.随机对奖品进行抽奖,并输出对应奖品的获奖者,以及未获奖的名单
*/
public class RandomTest01 {
public static void main(String[] args) {
// 创建Scanner对象用于读取用户输入
Scanner scanner = new Scanner(System.in);
// 创建Random对象用于生成随机数
Random random = new Random();
// 1. 输入参与者信息
// 提示用户输入参与抽奖的人数
System.out.print("请输入参与抽奖的人数: ");
// 读取用户输入的人数
int canjiaYhCount = scanner.nextInt();
/*
当使用scanner.nextInt()读取整数后输入缓冲区中会留下用户按下的换行符Enter 键)。
例如用户输入5并按 EnternextInt()会读取5但换行符\n仍留在缓冲区中。
*/
scanner.nextLine(); // 消耗换行符,避免影响后续输入
// 创建存储参与者姓名的数组
String[] canjiaYhArr = new String[canjiaYhCount];
// 循环读取每个参与者的姓名
for (int i = 0; i < canjiaYhCount; i++) {
// 提示输入参与者姓名
System.out.print("请输入第 " + (i + 1) + " 位参与者姓名: ");
// 读取并存储参与者姓名
canjiaYhArr[i] = scanner.nextLine();
}
// 2. 设置奖项
// 提示用户输入奖项数量
System.out.print("请输入奖项数量: ");
// 读取用户输入的奖项数量
int prizeCount = scanner.nextInt();
// 消耗换行符
scanner.nextLine();
// 创建存储奖项名称的数组
String[] prizeArr = new String[prizeCount];
// 循环读取每个奖项的名称
for (int i = 0; i < prizeCount; i++) {
// 提示输入奖项名称
System.out.print("请输入第 " + (i + 1) + " 个奖项名称: ");
// 读取并存储奖项名称
prizeArr[i] = scanner.nextLine();
}
// 3. 开始抽奖
System.out.println("=== 开始抽奖 ===");
// 标记数组,记录每个参与者是否已中奖
boolean[] isWinnerArr = new boolean[canjiaYhCount];
// 存储获奖者的数组
String[] winners = new String[prizeCount];
// 循环抽取每个奖项的获得者
for (int i = 0; i < prizeCount; i++) {
// 如果参与者人数少于奖项数,提前结束抽奖
if (i >= canjiaYhCount) {
System.out.println("奖项数量超过参与者人数,抽奖结束。");
break;
}
//记录获奖者的索引
int winnerIndex;
// 生成未中奖的随机索(获奖者可能重复获奖并且要优先获取获奖索引后再判断是否获奖所以用do-while)
do {
// 生成0到canjiaYhCount-1之间的随机整数
winnerIndex = random.nextInt(canjiaYhCount);
// 如果该索引的参与者已中奖,则重新生成
} while (isWinnerArr[winnerIndex]);
// 标记该参与者已中奖
isWinnerArr[winnerIndex] = true;
winners[i] = canjiaYhArr[winnerIndex]; // 记录获奖者姓名
System.out.println("恭喜 " + winners[i] + " 获得 " + prizeArr[i] + "!"); // 输出中奖信息
}
// 4. 查看中奖名单
System.out.println("\n=== 中奖名单 ===");
// 遍历并输出所有奖项的中奖者
for (int i = 0; i < Math.min(prizeCount, canjiaYhCount); i++) {
System.out.println(prizeArr[i] + ": " + winners[i]); // 输出奖项和对应的获奖者
}
// 5. 查看未中奖者
System.out.println("\n=== 未中奖者名单 ===");
// 遍历所有参与者,输出未中奖者
for (int i = 0; i < canjiaYhCount; i++) {
// 如果该参与者未中奖
if (!isWinnerArr[i]) {
// 输出未中奖者姓名
System.out.println(canjiaYhArr[i]);
}
}
// 关闭Scanner释放资源
scanner.close();
}
}

View File

@@ -0,0 +1,71 @@
package com.inmind.test07;
public class Student implements Comparable<Student>{
@Override
public int compareTo(Student o) {
return this.id - o.id;
}
private int id;
private String name;
private int age;
private String address;
public Student() {}
public Student(int id, String name, int age, String address) {
this.id = id;
this.name = name;
this.age = age;
this.address = address;
}
// Getters and setters
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String showMsg() {
return "Student{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", age=" + age +
", address='" + address + '\'' +
'}';
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
'}';
}
}

View File

@@ -0,0 +1,122 @@
package com.inmind.test07;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class StudentManager {
private List<Student> students;
public StudentManager() {
this.students = new ArrayList<>();
}
// 添加学生
public void addStudent(Student student) {
//判断学号是否存在
for (int i = 0; i < students.size(); i++) {
Student s = students.get(i);
if(s.getId() == student.getId()) {
System.out.println("该学生已存在!");
return;
}
}
students.add(student);
System.out.println("学生添加成功!");
}
// 删除学生
public void deleteStudent(int id) {
Student studentToRemove = null;
for (Student student : students) {
if (student.getId()== (id)) {
studentToRemove = student;
break;
}
}
if (studentToRemove != null) {
students.remove(studentToRemove);
System.out.println("学生删除成功!");
} else {
System.out.println("未找到该学生!");
}
}
// 修改学生信息
public void updateStudent(int id) {
Student studentToUpdate = null;
for (Student student : students) {
if (student.getId()== (id)) {
studentToUpdate = student;
break;
}
}
if (studentToUpdate != null) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入新姓名(不修改请直接回车):");
String name = scanner.nextLine();
if (!name.isEmpty()) {
studentToUpdate.setName(name);
}
System.out.print("请输入新年龄(不修改请直接回车):");
String ageStr = scanner.nextLine();
if (!ageStr.isEmpty()) {
try {
int age = Integer.parseInt(ageStr);
studentToUpdate.setAge(age);
} catch (NumberFormatException e) {
System.out.println("年龄输入无效,未修改!");
}
}
System.out.print("请输入新地址(不修改请直接回车):");
String address = scanner.nextLine();
if (!address.isEmpty()) {
studentToUpdate.setAddress(address);
}
System.out.println("学生信息修改成功!");
} else {
System.out.println("未找到该学生!");
}
}
// 查找学生
public void findStudent(int id) {
boolean found = false;
for (Student student : students) {
if (student.getId() == (id)) {
System.out.println("找到学生:" + student);
found = true;
break;
}
}
if (!found) {
System.out.println("未找到该学生!");
}
}
// 显示所有学生
public void displayAllStudents() {
if (students.isEmpty()) {
System.out.println("暂无学生信息!");
return;
}
System.out.println("所有学生信息如下:");
for (Student student : students) {
System.out.println(student.showMsg());
}
}
// 获取学生列表
public List<Student> getStudents() {
return students;
}
}

View File

@@ -0,0 +1,80 @@
package com.inmind.test07;
import java.util.ArrayList;
import java.util.Random;
public class Test6 {
public static void main(String[] args) {
int n = 15;
ArrayList<Card> cards = randomCard(n);
if (cards != null) {
System.out.println("随机"+ n +"张牌:" );
for (int i = 0; i < cards.size(); i++) {
Card card = cards.get(i);
card.showCard();
}
}else {
System.out.println(n+"超越范围,无法获取牌" );
}
/*System.out.println();
System.out.println();
int n2 = 55;
ArrayList<Card> cards2 = randomCard(n2);
if (cards2 != null) {
System.out.println("随机"+ n2 +"张牌:" );
for (int i = 0; i < cards.size(); i++) {
Card card = cards.get(i);
card.showCard();
}
}else {
System.out.println("随机"+ n2 +"张牌:\r\n超越范围,无法获取" );
}*/
}
public static ArrayList<Card> randomCard(int n) {
if (n > 54 || n < 0)
return null;
ArrayList<Card> rList = new ArrayList<>();
ArrayList<Card> cards = allCard();
Random r = new Random();
for (int i = 0; i < n; i++) {
int index = r.nextInt(cards.size());
Card rCard = cards.remove(index);
rList.add(rCard);
}
return rList;
}
public static ArrayList<Card> allCard() {
ArrayList<Card> allList = new ArrayList<>();
// 花色数组
String[] hs = {"黑桃", "红桃", "梅花", "方片"};
// 点数数组
String[] ds = {"A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"};
for (int H = 0; H < hs.length; H++) {
for (int d = 0; d < ds.length; d++) {
Card card = new Card(hs[H], ds[d]);
// 添加到集合
allList.add(card);
}
}
return allList;
}
}
class Card {
private String ds; // 点数
private String hs; // 花色
public Card(String ds, String hs) {
this.ds = ds;
this.hs = hs;
}
public void showCard() {
System.out.print(ds + hs+" ");
}
}

View File

@@ -0,0 +1,65 @@
package com.inmind.test07;
import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;
public class Test8 {
public static void main(String[] args) {
ArrayList<Integer> lotNumList = lotNum();
System.out.println("乐透号码已经生成,游戏开始:");
ArrayList<Integer> inputList = inputNum();
System.out.println("您输入的号码为:"+inputList);
int count = countNum(inputList , lotNumList);
System.out.println("乐透号码为:"+lotNumList);
System.out.println("猜中了:"+count+"个数字");
}
private static int countNum(ArrayList<Integer> inputList, ArrayList<Integer> lotNumList) {
int count = 0;
for (int i = 0; i < inputList.size(); i++) {
Integer num = inputList.get(i);
if (lotNumList.contains(num)){
count++;
}
}
return count ;
}
public static ArrayList<Integer> inputNum(){
ArrayList<Integer> list = new ArrayList<>();
Scanner sc = new Scanner(System.in);
for (int i = 0; i < 10; i++) {
System.out.println("请输入数字:");
int num = sc.nextInt();
if (num <= 0 || num > 50) {
i--;
System.out.println("输入无效数字,请重新输入");
continue;
}
if (!list.contains(num)){
list.add(num);
}else{
System.out.println(num+"重复录入数字无效,请重新输入");
i--;
}
}
return list;
}
public static ArrayList<Integer> lotNum(){
ArrayList<Integer> list = new ArrayList<>();
Random r = new Random();
for (int i = 0; i < 10; i++) {
int num = r.nextInt(50) + 1;
if (!list.contains(num)){
list.add(num);
}else{
i--;
}
}
return list;
}
}

View File

@@ -0,0 +1,53 @@
package com.inmind.test08;
class Student {
private String name; // 学生姓名
private double grade; // 学生成绩
// 静态变量:学生总人数
public static int totalStudents = 0;
// 静态变量:所有学生的总成绩
public static double totalGrades = 0;
// 静态代码块,用于初始化类加载时的操作
static {
System.out.println("学生成绩管理系统初始化中...");
}
// 构造方法
public Student(String name, double grade) {
this.name = name;
this.grade = grade;
totalStudents++; // 每创建一个学生对象总人数加1
totalGrades += grade; // 累加总成绩
}
// 获取学生姓名
public String getName() {
return name;
}
// 获取学生成绩
public double getGrade() {
return grade;
}
// 设置学生成绩
public void setGrade(double grade) {
// 更新总成绩:减去旧成绩,加上新成绩
totalGrades = totalGrades - this.grade + grade;
this.grade = grade;
}
// 静态方法:计算平均分
public static double calculateAverageGrade() {
if (totalStudents == 0) return 0;
return totalGrades / totalStudents;
}
// 静态方法:重置学生统计信息
public static void resetStatistics() {
totalStudents = 0;
totalGrades = 0;
}
}

View File

@@ -0,0 +1,117 @@
package com.inmind.test08;
import java.util.Arrays;
import java.util.Scanner;
public class StudentGradeSystem {
// 定义最大学生数量的常量
private static final int MAX_STUDENTS = 20;
// 存储学生姓名的数组
private static String[] names = new String[MAX_STUDENTS];
// 存储学生成绩的数组
private static double[] grades = new double[MAX_STUDENTS];
// 当前学生数量计数器
private static int count = 0;
public static void main(String[] args) {
// 创建Scanner对象用于用户输入
Scanner scanner = new Scanner(System.in);
// 主循环,持续显示菜单直到用户选择退出
while (true) {
System.out.println("1. 添加学生 2. 查看列表 3. 统计分析 4. 退出");
System.out.println("请选择: ");
int choice = scanner.nextInt();
scanner.nextLine(); // 消耗换行符,避免影响后续输入
// 根据用户选择执行相应操作
switch (choice) {
case 1:
addStudent(scanner);
break;
case 2:
printStudents();
break;
case 3:
analyzeGrades();
break;
case 4:
System.out.println("退出系统");
return; // 结束程序
}
}
}
// 添加学生信息的方法
private static void addStudent(Scanner scanner) {
// 检查是否达到最大学生数量
if (count >= MAX_STUDENTS) {
System.out.println("学生数量已满");
return;
}
// 获取用户输入的姓名
System.out.print("输入姓名: ");
String name = scanner.nextLine();
// 获取用户输入的成绩
System.out.print("输入成绩: ");
double grade = scanner.nextDouble();
scanner.nextLine(); // 消耗换行符
// 将学生信息添加到数组中
names[count] = name;
grades[count] = grade;
count++; // 学生数量加1
System.out.println("添加成功");
}
// 打印所有学生信息的方法
private static void printStudents() {
// 检查是否有学生数据
if (count == 0) {
System.out.println("暂无学生数据");
return;
}
System.out.println("\n学生列表:");
// 遍历学生数组并格式化输出
for (int i = 0; i < count; i++) {
// System.out.printf("%d. %-8s %.1f\n", i + 1, names[i], grades[i]);
System.out.println((i+1)+". "+names[i]+" "+grades[i]);
}
}
// 分析学生成绩的方法
private static void analyzeGrades() {
// 检查是否有学生数据
if (count == 0) {
System.out.println("暂无学生数据");
return;
}
double sum = 0; // 成绩总和
double max = grades[0]; // 最高分,初始化为第一个学生成绩
double min = grades[0]; // 最低分,初始化为第一个学生成绩
// 计算总分、最高分和最低分
for (double grade : grades) {
sum += grade;
if (grade > max) max = grade;
if (grade < min) min = grade;
}
double avg = sum / count; // 计算平均分
avg = Math.round(avg * 100) / 100.0;
// 复制成绩数组并排序
double[] sortedGrades = Arrays.copyOf(grades, count);
Arrays.sort(sortedGrades);
// 输出统计结果
System.out.println("平均分: "+avg);
System.out.println("最高分: "+ max);
System.out.println("最低分: "+ min);
System.out.println("成绩排序: " + Arrays.toString(sortedGrades));
}
}

View File

@@ -0,0 +1,126 @@
package com.inmind.test08;
import java.util.Arrays;
import java.util.Scanner;
public class StudentGradeSystem2 {
private static final int MAX_STUDENTS = 20;
private static Student[] students = new Student[MAX_STUDENTS];
private static int count = 0;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("\n1. 添加学生 2. 查看列表 3. 统计分析 4. 修改成绩 5. 退出");
System.out.print("请选择: ");
int choice = scanner.nextInt();
scanner.nextLine(); // 消耗换行符
switch (choice) {
case 1:
addStudent(scanner);
break;
case 2:
printStudents();
break;
case 3:
analyzeGrades();
break;
case 4:
modifyGrade(scanner);
break;
case 5:
System.out.println("退出系统");
return;
}
}
}
private static void addStudent(Scanner scanner) {
if (count >= MAX_STUDENTS) {
System.out.println("学生数量已满");
return;
}
System.out.print("输入姓名: ");
String name = scanner.nextLine();
System.out.print("输入成绩: ");
double grade = scanner.nextDouble();
scanner.nextLine();
students[count] = new Student(name, grade);
count++;
System.out.println("添加成功");
}
private static void printStudents() {
if (count == 0) {
System.out.println("暂无学生数据");
return;
}
System.out.println("\n学生列表:");
for (int i = 0; i < count; i++) {
Student student = students[i];
System.out.printf("%d. %-8s %.1f\n", i + 1, student.getName(), student.getGrade());
}
}
private static void analyzeGrades() {
if (count == 0) {
System.out.println("暂无学生数据");
return;
}
// 使用Student类的静态方法获取平均分
double avg = Student.calculateAverageGrade();
// 计算最高分和最低分
double max = students[0].getGrade();
double min = students[0].getGrade();
for (int i = 1; i < count; i++) {
double grade = students[i].getGrade();
if (grade > max) max = grade;
if (grade < min) min = grade;
}
// 复制成绩数组并排序
double[] sortedGrades = new double[count];
for (int i = 0; i < count; i++) {
sortedGrades[i] = students[i].getGrade();
}
Arrays.sort(sortedGrades);
// 输出统计结果
System.out.printf("\n平均分: %.2f\n", avg);
System.out.printf("最高分: %.2f\n", max);
System.out.printf("最低分: %.2f\n", min);
System.out.println("成绩排序: " + Arrays.toString(sortedGrades));
System.out.printf("学生总数: %d\n", Student.totalStudents);
}
private static void modifyGrade(Scanner scanner) {
System.out.print("请输入要修改成绩的学生姓名: ");
String name = scanner.nextLine();
for (int i = 0; i < count; i++) {
if (students[i].getName().equalsIgnoreCase(name)) {
System.out.printf("当前成绩: %.1f\n", students[i].getGrade());
System.out.print("输入新成绩: ");
double newGrade = scanner.nextDouble();
scanner.nextLine();
students[i].setGrade(newGrade);
System.out.println("成绩修改成功");
return;
}
}
System.out.println("未找到该学生");
}
}

View File

@@ -0,0 +1,242 @@
package com.inmind.test09;
public class Test {
public static void main(String[] args) {
// 创建员工管理系统实例
EmployeeManager manager = new EmployeeManager();
// 添加不同类型的员工到系统中
manager.addEmployee(new Developer("张三", "D001", "Java"));
manager.addEmployee(new Designer("李四", "D002", "UI/UX"));
manager.addEmployee(new Tester("王五", "T001", "自动化测试"));
// 显示公司所有员工的详细信息
System.out.println("公司员工列表:");
manager.displayAllEmployees();
// 计算并显示公司本月的工资总支出
System.out.println("\n本月公司工资总支出" + manager.calculateTotalSalary() + "");
// 创建一个新项目并安排员工任务
System.out.println("\n项目任务安排");
Project project = new Project("企业管理系统", "2025-07-20", "2025-12-31");
manager.assignProjectTasks(project);
}
}
/**
* 员工抽象类 - 定义所有员工的通用属性和行为
* 不能直接实例化,必须由具体子类实现
*/
abstract class Employee {
private String name; // 员工姓名
private String employeeId; // 员工工号
private double baseSalary; // 基本工资
// 构造函数,初始化员工基本信息
public Employee(String name, String employeeId, double baseSalary) {
this.name = name;
this.employeeId = employeeId;
this.baseSalary = baseSalary;
}
// 抽象方法:计算员工工资(由子类根据具体职位实现)
public abstract double calculateSalary();
// 抽象方法:执行工作(由子类根据具体职责实现)
public abstract void performWork();
// 获取员工姓名
public String getName() {
return name;
}
// 获取员工工号
public String getEmployeeId() {
return employeeId;
}
// 获取员工基本工资
public double getBaseSalary() {
return baseSalary;
}
// 重写toString方法返回员工信息的字符串表示
@Override
public String toString() {
return "姓名:" + name +
",工号:" + employeeId +
",职位:" + this.getClass().getSimpleName() +
",月薪:" + calculateSalary() + "";
}
}
/**
* 开发人员类 - 继承自Employee
* 具体实现开发人员的工资计算和工作内容
*/
class Developer extends Employee {
private String programmingLanguage; // 开发使用的编程语言
// 构造函数,初始化开发人员信息
public Developer(String name, String employeeId, String programmingLanguage) {
super(name, employeeId, 15000); // 调用父类构造函数设置基本工资
this.programmingLanguage = programmingLanguage;
}
// 实现父类的抽象方法:计算开发人员工资(基本工资 + 技术津贴)
@Override
public double calculateSalary() {
return getBaseSalary() + (programmingLanguage.equals("Java") ? 2000 : 1500);
}
// 实现父类的抽象方法:描述开发人员的工作内容
@Override
public void performWork() {
System.out.println(getName() + "正在使用" + programmingLanguage + "编写代码");
}
// 获取开发人员使用的编程语言
public String getProgrammingLanguage() {
return programmingLanguage;
}
}
/**
* 设计人员类 - 继承自Employee
* 具体实现设计人员的工资计算和工作内容
*/
class Designer extends Employee {
private String designTool; // 设计使用的工具
// 构造函数,初始化设计人员信息
public Designer(String name, String employeeId, String designTool) {
super(name, employeeId, 13000); // 调用父类构造函数设置基本工资
this.designTool = designTool;
}
// 实现父类的抽象方法:计算设计人员工资(基本工资 + 设计津贴)
@Override
public double calculateSalary() {
return getBaseSalary() + (designTool.equals("UI/UX") ? 1800 : 1200);
}
// 实现父类的抽象方法:描述设计人员的工作内容
@Override
public void performWork() {
System.out.println(getName() + "正在使用" + designTool + "进行设计工作");
}
// 获取设计人员使用的设计工具
public String getDesignTool() {
return designTool;
}
}
/**
* 测试人员类 - 继承自Employee
* 具体实现测试人员的工资计算和工作内容
*/
class Tester extends Employee {
private String testingMethod; // 测试方法
// 构造函数,初始化测试人员信息
public Tester(String name, String employeeId, String testingMethod) {
super(name, employeeId, 12000); // 调用父类构造函数设置基本工资
this.testingMethod = testingMethod;
}
// 实现父类的抽象方法:计算测试人员工资(基本工资 + 测试津贴)
@Override
public double calculateSalary() {
return getBaseSalary() + (testingMethod.equals("自动化测试") ? 2500 : 1500);
}
// 实现父类的抽象方法:描述测试人员的工作内容
@Override
public void performWork() {
System.out.println(getName() + "正在进行" + testingMethod + "工作");
}
// 获取测试人员使用的测试方法
public String getTestingMethod() {
return testingMethod;
}
}
/**
* 员工管理类 - 负责管理公司员工信息和项目任务分配
*/
class EmployeeManager {
private Employee[] employees = new Employee[10]; // 员工数组最多容纳10名员工
private int employeeCount = 0; // 当前员工数量
// 添加员工到系统中
public void addEmployee(Employee employee) {
if (employeeCount < employees.length) {
employees[employeeCount++] = employee;
} else {
System.out.println("员工列表已满,无法添加更多员工");
}
}
// 显示所有员工信息
public void displayAllEmployees() {
for (int i = 0; i < employeeCount; i++) {
System.out.println(employees[i]);
}
}
// 计算所有员工的总工资
public double calculateTotalSalary() {
double total = 0;
for (int i = 0; i < employeeCount; i++) {
total += employees[i].calculateSalary();
}
return total;
}
// 为项目分配任务给员工
public void assignProjectTasks(Project project) {
System.out.println("项目名称:" + project.getProjectName());
System.out.println("开始日期:" + project.getStartDate());
System.out.println("结束日期:" + project.getEndDate());
System.out.println("任务分配:");
// 遍历所有员工,分配各自的任务
for (int i = 0; i < employeeCount; i++) {
employees[i].performWork();
}
}
}
/**
* 项目类 - 定义项目的基本信息
*/
class Project {
private String projectName; // 项目名称
private String startDate; // 开始日期
private String endDate; // 结束日期
// 构造函数,初始化项目信息
public Project(String projectName, String startDate, String endDate) {
this.projectName = projectName;
this.startDate = startDate;
this.endDate = endDate;
}
// 获取项目名称
public String getProjectName() {
return projectName;
}
// 获取项目开始日期
public String getStartDate() {
return startDate;
}
// 获取项目结束日期
public String getEndDate() {
return endDate;
}
}

View File

@@ -0,0 +1,26 @@
package com.inmind.test10;
// 可充电接口
public interface Chargeable {
// 抽象方法:充电
void charge(int minutes);
// 抽象方法:获取剩余电量
int getBatteryPercentage();
// 私有静态方法:电量检查工具方法
private static boolean isBatteryValid(int percentage) {
return percentage >= 0 && percentage <= 100;
}
// 默认方法:显示电量
default void showBatteryStatus() {
int battery = getBatteryPercentage();
if (isBatteryValid(battery)) {
System.out.println("当前电量: " + battery + "%");
} else {
System.out.println("电量数据异常");
}
}
}

View File

@@ -0,0 +1,77 @@
package com.inmind.test10;
// 设备抽象基类
public abstract class Device {
// 成员变量
protected String brand;
protected String model;
protected double price;
protected boolean isPowerOn;
// 静态变量:统计设备总数
public static int totalDevices = 0;
// 构造方法
public Device(String brand, String model, double price) {
this.brand = brand;
this.model = model;
this.price = price;
this.isPowerOn = false;
totalDevices++;
}
// 抽象方法:设备功能介绍
public abstract void introduce();
// 开机方法
public void powerOn() {
if (!isPowerOn) {
isPowerOn = true;
System.out.println(brand + " " + model + " 已开机");
} else {
System.out.println(brand + " " + model + " 已经是开机状态");
}
}
// 关机方法
public void powerOff() {
if (isPowerOn) {
isPowerOn = false;
System.out.println(brand + " " + model + " 已关机");
} else {
System.out.println(brand + " " + model + " 已经是关机状态");
}
}
// 静态方法:获取设备总数
public static int getTotalDevices() {
return totalDevices;
}
// 静态方法:计算折扣价格
/*public static double calculateDiscountPrice(Device device, double discountRate) {
if (discountRate < 0.1 || discountRate > 1.0) {
System.out.println("折扣率无效必须在0.1-1.0之间");
return device.price;
}
return device.price * discountRate;
}*/
// getter方法
public String getBrand() {
return brand;
}
public String getModel() {
return model;
}
public double getPrice() {
return price;
}
public boolean isPowerOn() {
return isPowerOn;
}
}

View File

@@ -0,0 +1,121 @@
package com.inmind.test10;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
// 设备管理器类
public class DeviceManager {
private List<Device> devices; // 存储设备的集合
public DeviceManager() {
devices = new ArrayList<>();
}
// 添加设备
public void addDevice(Device device) {
if (device != null) {
devices.add(device);
System.out.println("已添加设备: " + device.getBrand() + " " + device.getModel());
}
}
// 移除设备
public boolean removeDevice(String brand, String model) {
for (int i = 0; i < devices.size(); i++) {
Device device = devices.get(i);
if (device.getBrand().equals(brand) && device.getModel().equals(model)) {
devices.remove(i);
System.out.println("已移除设备: " + brand + " " + model);
Device.totalDevices --;
return true;
}
}
System.out.println("未找到设备: " + brand + " " + model);
return false;
}
// 显示所有设备
public void showAllDevices() {
System.out.println("\n===== 所有设备列表 =====");
if (devices.isEmpty()) {
System.out.println("没有任何设备");
return;
}
for (int i = 0; i < devices.size(); i++) {
System.out.print((i + 1) + ". ");
devices.get(i).introduce();
}
}
// 开机所有设备
public void powerOnAllDevices() {
System.out.println("\n===== 开机所有设备 =====");
for (Device device : devices) {
device.powerOn();
}
}
// 关机所有设备
public void powerOffAllDevices() {
System.out.println("\n===== 关机所有设备 =====");
for (Device device : devices) {
device.powerOff();
}
}
// 为所有可充电设备充电
public void chargeAllChargeableDevices(int minutes) {
System.out.println("\n===== 为可充电设备充电 =====");
for (Device device : devices) {
if (device instanceof Chargeable) {
Chargeable chargeable = (Chargeable) device;
chargeable.charge(minutes);
chargeable.showBatteryStatus();
}
}
}
// 按价格排序设备
public void sortDevicesByPrice() {
System.out.println("\n===== 按价格排序设备 =====");
// 使用匿名内部类实现Comparator接口
Collections.sort(devices, new Comparator<Device>() {
@Override
public int compare(Device d1, Device d2) {
// 按价格升序排序
return Double.compare(d1.getPrice(), d2.getPrice());
}
});
}
// 查找特定品牌的设备
public List<Device> findDevicesByBrand(String brand) {
List<Device> result = new ArrayList<>();
for (Device device : devices) {
if (device.getBrand().equals(brand)) {
result.add(device);
}
}
return result;
}
// 显示所有可充电设备
public void showChargeableDevices() {
System.out.println("\n===== 可充电设备 =====");
boolean hasChargeable = false;
for (Device device : devices) {
if (device instanceof Chargeable) {
hasChargeable = true;
device.introduce();
((Chargeable) device).showBatteryStatus();
}
}
if (!hasChargeable) {
System.out.println("没有可充电设备");
}
}
}

View File

@@ -0,0 +1,65 @@
package com.inmind.test10;
import java.util.List;
// 测试类
public class DeviceTest {
public static void main(String[] args) {
// 创建设备管理器
DeviceManager manager = new DeviceManager();
// 添加设备
manager.addDevice(new Smartphone("Apple", "iPhone 14", 6999.0, 256));
manager.addDevice(new Laptop("Dell", "XPS 15", 9999.0, 32));
manager.addDevice(new SmartTV("Sony", "KD-65X9000H", 7999.0, 65.0));
manager.addDevice(new Smartphone("Samsung", "Galaxy S23", 5999.0, 512));
manager.addDevice(new Laptop("Lenovo", "ThinkPad X1", 8999.0, 16));
// 显示所有设备
manager.showAllDevices();
// 显示设备总数(静态方法使用)
System.out.println("\n当前设备总数: " + Device.getTotalDevices());
// 开机所有设备
manager.powerOnAllDevices();
// 为所有可充电设备充电60分钟
manager.chargeAllChargeableDevices(60);
// 显示可充电设备及其电量
manager.showChargeableDevices();
// 按价格排序并显示
/*manager.sortDevicesByPrice();
manager.showAllDevices();*/
// 测试多态:调用特定设备的方法
System.out.println("\n===== 设备功能测试 =====");
List<Device> appleDevices = manager.findDevicesByBrand("Apple");
for (Device device : appleDevices) {
if (device instanceof Smartphone) {
Smartphone phone = (Smartphone) device;
phone.connectToNetwork("家庭WiFi");
phone.takePhoto();
phone.showBatteryStatus();
phone.disconnectFromNetwork();
}
}
// 测试静态方法:计算折扣价格
/*Device laptop = manager.findDevicesByBrand("Dell").get(0);
double discountPrice = Device.calculateDiscountPrice(laptop, 0.8);
System.out.println("\n" + laptop.getBrand() + " " + laptop.getModel() +
" 原价: " + laptop.getPrice() + " 折扣价: " + discountPrice);*/
// 关机所有设备
manager.powerOffAllDevices();
// 移除一个设备
manager.removeDevice("Sony", "KD-65X9000H");
manager.showAllDevices();
}
}

View File

@@ -0,0 +1,69 @@
package com.inmind.test10;
// 笔记本电脑类 - 实现两个接口
public class Laptop extends Device implements Networkable, Chargeable {
private int ramSize; // 内存大小(GB)
private int batteryLevel; // 电池电量(%)
public Laptop(String brand, String model, double price, int ramSize) {
super(brand, model, price);
this.ramSize = ramSize;
this.batteryLevel = 70; // 初始电量70%
}
@Override
public void introduce() {
System.out.println("这是一台" + brand + " " + model + "笔记本电脑,价格" + price +
"元,内存大小" + ramSize + "GB");
}
// 特有方法:运行程序
public void runProgram(String programName) {
if (isPowerOn()) {
System.out.println(brand + " " + model + " 正在运行 " + programName);
batteryLevel -= 10; // 运行程序消耗电量
} else {
System.out.println("请先开机再运行程序");
}
}
// 实现Networkable接口方法
@Override
public void connectToNetwork(String networkName) {
if (isPowerOn() && Networkable.isNetworkAvailable()) {
System.out.println(brand + " " + model + " 已连接到 " + networkName);
} else if (!isPowerOn()) {
System.out.println("请先开机再连接网络");
} else {
System.out.println("网络不可用,无法连接到 " + networkName);
}
}
@Override
public void disconnectFromNetwork() {
System.out.println(brand + " " + model + " 已断开网络连接");
}
// 实现Chargeable接口方法
@Override
public void charge(int minutes) {
if (minutes <= 0) {
System.out.println("充电时间必须为正数");
return;
}
System.out.println(brand + " " + model + " 正在充电" + minutes + "分钟");
int chargeAmount = minutes / 5; // 每5分钟充1%
batteryLevel += chargeAmount;
if (batteryLevel > 100) {
batteryLevel = 100;
}
}
@Override
public int getBatteryPercentage() {
return batteryLevel;
}
}

View File

@@ -0,0 +1,17 @@
package com.inmind.test10;
// 可联网接口
public interface Networkable {
// 抽象方法:连接网络
void connectToNetwork(String networkName);
// 抽象方法:断开网络
void disconnectFromNetwork();
// 静态方法:检查网络可用性
static boolean isNetworkAvailable() {
// 模拟网络检查
return Math.random() > 0.2; // 80%概率网络可用
}
}

View File

@@ -0,0 +1,44 @@
package com.inmind.test10;
// 智能电视类 - 实现一个接口
public class SmartTV extends Device implements Networkable {
private double screenSize; // 屏幕尺寸(英寸)
public SmartTV(String brand, String model, double price, double screenSize) {
super(brand, model, price);
this.screenSize = screenSize;
}
@Override
public void introduce() {
System.out.println("这是一台" + brand + " " + model + "智能电视,价格" + price +
"元,屏幕尺寸" + screenSize + "英寸");
}
// 特有方法:播放视频
public void playVideo(String videoName) {
if (isPowerOn()) {
System.out.println(brand + " " + model + " 正在播放 " + videoName);
} else {
System.out.println("请先开机再播放视频");
}
}
// 实现Networkable接口方法
@Override
public void connectToNetwork(String networkName) {
if (isPowerOn() && Networkable.isNetworkAvailable()) {
System.out.println(brand + " " + model + " 已连接到 " + networkName);
} else if (!isPowerOn()) {
System.out.println("请先开机再连接网络");
} else {
System.out.println("网络不可用,无法连接到 " + networkName);
}
}
@Override
public void disconnectFromNetwork() {
System.out.println(brand + " " + model + " 已断开网络连接");
}
}

View File

@@ -0,0 +1,69 @@
package com.inmind.test10;
// 智能手机类 - 实现两个接口
public class Smartphone extends Device implements Networkable, Chargeable {
private int storage; // 存储容量(GB)
private int batteryLevel; // 电池电量(%)
public Smartphone(String brand, String model, double price, int storage) {
super(brand, model, price);
this.storage = storage;
this.batteryLevel = 50; // 初始电量50%
}
@Override
public void introduce() {
System.out.println("这是一部" + brand + " " + model + "智能手机,价格" + price +
"元,存储容量" + storage + "GB");
}
// 特有方法:拍照
public void takePhoto() {
if (isPowerOn()) {
System.out.println(brand + " " + model + " 正在拍照");
batteryLevel -= 5; // 拍照消耗电量
} else {
System.out.println("请先开机再拍照");
}
}
// 实现Networkable接口方法
@Override
public void connectToNetwork(String networkName) {
if (isPowerOn() && Networkable.isNetworkAvailable()) {
System.out.println(brand + " " + model + " 已连接到 " + networkName);
} else if (!isPowerOn()) {
System.out.println("请先开机再连接网络");
} else {
System.out.println("网络不可用,无法连接到 " + networkName);
}
}
@Override
public void disconnectFromNetwork() {
System.out.println(brand + " " + model + " 已断开网络连接");
}
// 实现Chargeable接口方法
@Override
public void charge(int minutes) {
if (minutes <= 0) {
System.out.println("充电时间必须为正数");
return;
}
System.out.println(brand + " " + model + " 正在充电" + minutes + "分钟");
int chargeAmount = minutes / 2; // 每2分钟充1%
batteryLevel += chargeAmount;
if (batteryLevel > 100) {
batteryLevel = 100;
}
}
@Override
public int getBatteryPercentage() {
return batteryLevel;
}
}

View File

@@ -0,0 +1,299 @@
package com.inmind.test11;// 导入所需的Java工具类
import java.util.ArrayList; // 用于创建动态数组
import java.util.List; // 用于定义列表接口
import java.util.Random; // 用于生成随机数(本案例未直接使用,预留扩展)
// 武器接口 - 定义所有武器的共同行为
interface Weapon {
// 开火方法,参数为攻击目标玩家
void fire(Player target);
// 换弹方法
void reload();
// 获取武器名称
String getName();
// 获取武器伤害值
int getDamage();
// 获取当前弹夹剩余弹药
int getAmmoCount();
}
// 玩家类 - 代表游戏中的玩家角色
class Player {
private String name; // 玩家名称
private int hp; // 玩家生命值
private List<Weapon> weapons; // 玩家持有的武器列表
private Weapon currentWeapon; // 当前使用的武器
// 构造方法 - 初始化玩家名称和生命值
public Player(String name) {
this.name = name;
this.hp = 100; // 初始生命值设为100
this.weapons = new ArrayList<>(); // 初始化武器列表
}
// 拾取武器方法 - 将武器添加到玩家的武器库
public void pickUpWeapon(Weapon weapon) {
weapons.add(weapon); // 添加武器到列表
if (currentWeapon == null) { // 如果还没有当前武器
currentWeapon = weapon; // 自动装备该武器
}
System.out.println(name + "拾取了" + weapon.getName());
}
// 切换武器方法 - 接口作为参数
public void switchWeapon(Weapon weapon) {
// 检查玩家是否拥有该武器\
for (int i = 0; i < weapons.size(); i++) {
Weapon w = weapons.get(i);
if (w.getName().equals(weapon.getName())) {
currentWeapon = weapon; // 切换到该武器
System.out.println(name + "切换到" + weapon.getName());
return;
}
}
System.out.println(name + "没有该武器!");
/*if (weapons.contains(weapon)) {
currentWeapon = weapon; // 切换到该武器
System.out.println(name + "切换到" + weapon.getName());
} else {
System.out.println(name + "没有该武器!");
}*/
}
// 攻击目标玩家方法
public void attack(Player target) {
if (currentWeapon == null) { // 检查是否持有武器
System.out.println(name + "没有武器!");
return;
}
// 输出攻击信息
System.out.println("\n" + name + "使用" + currentWeapon.getName() + "攻击" + target.name);
currentWeapon.fire(target); // 使用当前武器攻击目标
// 如果弹药耗尽,自动换弹
if (currentWeapon.getAmmoCount() == 0) {
currentWeapon.reload();
}
}
// 受到伤害方法
public void takeDamage(int damage) {
// 计算剩余生命值,确保不会为负数
hp = Math.max(0, hp - damage);
System.out.println(name + "受到" + damage + "点伤害剩余HP" + hp);
// 如果生命值为0输出被淘汰信息
if (hp == 0) {
System.out.println(name + "被淘汰!");
}
}
// 获取玩家名称的方法
public String getName() {
return name;
}
public int getHp() {
return hp;
}
}
// 武器工厂类 - 用于创建各种武器实例(工厂模式)
class WeaponFactory {
// 创建武器的静态方法 - 接口作为返回值
public static Weapon createWeapon(String type) {
// 根据类型创建不同武器使用匿名内部类实现Weapon接口
switch (type.toLowerCase()) {
case "ak47": // 创建AK47步枪
return new Weapon() {
private int ammo = 30; // 当前弹药
private final int maxAmmo = 30; // 最大弹容量
@Override
public void fire(Player target) {
if (ammo <= 0) { // 检查弹药是否充足
System.out.println("弹药耗尽,请换弹!");
return;
}
ammo--; // 消耗1发弹药
target.takeDamage(42); // 造成42点伤害
System.out.println("🔫 AK47开火剩余弹药" + ammo);
}
@Override
public void reload() {
System.out.println("AK47换弹中...");
ammo = maxAmmo; // 装满弹药
}
@Override
public String getName() {
return "AK47";
}
@Override
public int getDamage() {
return 42;
}
@Override
public int getAmmoCount() {
return ammo;
}
};
case "awm": // 创建AWM狙击枪
return new Weapon() {
private int ammo = 10; // 当前弹药
private final int maxAmmo = 10; // 最大弹容量
@Override
public void fire(Player target) {
if (ammo <= 0) {
System.out.println("弹药耗尽,请换弹!");
return;
}
ammo--;
target.takeDamage(100); // 造成100点伤害狙击枪威力大
System.out.println("🎯 AWM开镜射击剩余弹药" + ammo);
}
@Override
public void reload() {
System.out.println("AWM换弹中...");
ammo = maxAmmo;
}
@Override
public String getName() {
return "AWM";
}
@Override
public int getDamage() {
return 100;
}
@Override
public int getAmmoCount() {
return ammo;
}
};
default: // 默认创建沙漠之鹰手枪
return new Weapon() {
private int ammo = 12; // 当前弹药
private final int maxAmmo = 12; // 最大弹容量
@Override
public void fire(Player target) {
if (ammo <= 0) {
System.out.println("弹药耗尽,请换弹!");
return;
}
ammo--;
target.takeDamage(25); // 造成25点伤害
System.out.println("🔫 沙漠之鹰开火!剩余弹药:" + ammo);
}
@Override
public void reload() {
System.out.println("沙漠之鹰换弹中...");
ammo = maxAmmo;
}
@Override
public String getName() {
return "沙漠之鹰";
}
@Override
public int getDamage() {
return 25;
}
@Override
public int getAmmoCount() {
return ammo;
}
};
}
}
}
// 主类 - 程序入口
public class CorssFire {
public static void main(String[] args) {
// 创建两个玩家
Player player1 = new Player("潜伏者-小明");
Player player2 = new Player("保卫者-小红");
// 玩家拾取武器(通过武器工厂创建)
player1.pickUpWeapon(WeaponFactory.createWeapon("ak47"));
player2.pickUpWeapon(WeaponFactory.createWeapon("awm"));
// 玩家2额外拾取M4A1使用匿名内部类直接创建武器
player2.pickUpWeapon(new Weapon() {
private int ammo = 30;
private final int maxAmmo = 30;
@Override
public void fire(Player target) {
if (ammo <= 0) {
System.out.println("弹药耗尽,请换弹!");
return;
}
ammo--;
target.takeDamage(30); // M4A1造成30点伤害
System.out.println("🔫 M4A1开火剩余弹药" + ammo);
}
@Override
public void reload() {
System.out.println("M4A1换弹中...");
ammo = maxAmmo;
}
@Override
public String getName() {
return "M4A1";
}
@Override
public int getDamage() {
return 30;
}
@Override
public int getAmmoCount() {
return ammo;
}
});
/*// 模拟对战过程
System.out.println("\n=== 开始对战 ===");
player1.attack(player2); // 玩家1攻击玩家2
player2.attack(player1); // 玩家2反击
player1.attack(player2); // 玩家1再次攻击*/
while (true){
// 模拟对战过程
System.out.println("\n=== 开始对战 ===");
player1.attack(player2); // 玩家1攻击玩家2
if (player2.getHp() == 0) {
break;
}
player2.attack(player1); // 玩家2反击
if (player1.getHp() == 0) {
break;
}
}
// 玩家2切换武器
player2.switchWeapon(WeaponFactory.createWeapon("awm"));
// player2.attack(player1); // 使用新武器攻击
}
}

View File

@@ -0,0 +1,261 @@
package com.inmind.test11_1;
import java.util.ArrayList;
import java.util.List;
// 武器接口
interface Weapon {
// 开火
void fire(Player target);
// 换弹
void reload();
// 获取武器名称
String getName();
// 获取伤害值
int getDamage();
// 获取当前弹夹容量
int getAmmoCount();
}
// 玩家类
class Player {
private String name;
private int hp;
private List<Weapon> weapons = new ArrayList<>();
private Weapon currentWeapon;
public Player(String name) {
this.name = name;
this.hp = 100;
}
// 拾取武器
public void pickUpWeapon(Weapon weapon) {
weapons.add(weapon);
if (currentWeapon == null) {
currentWeapon = weapon;
}
System.out.println(name + "拾取了" + weapon.getName());
}
// 切换武器(接口作为参数)
public void switchWeapon(Weapon weapon) {
if (weapons.contains(weapon)) {
currentWeapon = weapon;
System.out.println(name + "切换到" + weapon.getName());
} else {
System.out.println(name + "没有该武器!");
}
}
// 攻击目标
public void attack(Player target) {
if (currentWeapon == null) {
System.out.println(name + "没有武器!");
return;
}
System.out.println("\n" + name + "使用" + currentWeapon.getName() + "攻击" + target.name);
currentWeapon.fire(target);
if (currentWeapon.getAmmoCount() == 0) {
currentWeapon.reload();
}
}
// 受到伤害
public void takeDamage(int damage) {
hp = Math.max(0, hp - damage);
System.out.println(name + "受到" + damage + "点伤害剩余HP" + hp);
if (hp == 0) {
System.out.println(name + "被淘汰!");
}
}
public String getName() {
return name;
}
}
// 武器工厂
class WeaponFactory {
// 创建武器(接口作为返回值)
public static Weapon createWeapon(String type) {
switch (type.toLowerCase()) {
case "ak47":
return new Weapon() {
private int ammo = 30;
private final int maxAmmo = 30;
@Override
public void fire(Player target) {
if (ammo <= 0) {
System.out.println("弹药耗尽,请换弹!");
return;
}
ammo--;
target.takeDamage(42);
System.out.println("🔫 AK47开火剩余弹药" + ammo);
}
@Override
public void reload() {
System.out.println("AK47换弹中...");
ammo = maxAmmo;
}
@Override
public String getName() {
return "AK47";
}
@Override
public int getDamage() {
return 42;
}
@Override
public int getAmmoCount() {
return ammo;
}
};
case "awm":
return new Weapon() {
private int ammo = 10;
private final int maxAmmo = 10;
@Override
public void fire(Player target) {
if (ammo <= 0) {
System.out.println("弹药耗尽,请换弹!");
return;
}
ammo--;
target.takeDamage(100);
System.out.println("🎯 AWM开镜射击剩余弹药" + ammo);
}
@Override
public void reload() {
System.out.println("AWM换弹中...");
ammo = maxAmmo;
}
@Override
public String getName() {
return "AWM";
}
@Override
public int getDamage() {
return 100;
}
@Override
public int getAmmoCount() {
return ammo;
}
};
default:
return new Weapon() {
private int ammo = 12;
private final int maxAmmo = 12;
@Override
public void fire(Player target) {
if (ammo <= 0) {
System.out.println("弹药耗尽,请换弹!");
return;
}
ammo--;
target.takeDamage(25);
System.out.println("🔫 沙漠之鹰开火!剩余弹药:" + ammo);
}
@Override
public void reload() {
System.out.println("沙漠之鹰换弹中...");
ammo = maxAmmo;
}
@Override
public String getName() {
return "沙漠之鹰";
}
@Override
public int getDamage() {
return 25;
}
@Override
public int getAmmoCount() {
return ammo;
}
};
}
}
}
public class Test {
public static void main(String[] args) {
// 创建玩家
Player player1 = new Player("潜伏者-小明");
Player player2 = new Player("保卫者-小红");
// 拾取武器
player1.pickUpWeapon(WeaponFactory.createWeapon("ak47"));
player2.pickUpWeapon(WeaponFactory.createWeapon("awm"));
// 玩家2额外拾取手枪匿名内部类实现
player2.pickUpWeapon(new Weapon() {
private int ammo = 30;
private final int maxAmmo = 30;
@Override
public void fire(Player target) {
if (ammo <= 0) {
System.out.println("弹药耗尽,请换弹!");
return;
}
ammo--;
target.takeDamage(30);
System.out.println("🔫 M4A1开火剩余弹药" + ammo);
}
@Override
public void reload() {
System.out.println("M4A1换弹中...");
ammo = maxAmmo;
}
@Override
public String getName() {
return "M4A1";
}
@Override
public int getDamage() {
return 30;
}
@Override
public int getAmmoCount() {
return ammo;
}
});
// 模拟对战
System.out.println("\n=== 开始对战 ===");
player1.attack(player2);
player2.attack(player1);
player1.attack(player2);
// 切换武器
player2.switchWeapon(WeaponFactory.createWeapon("default"));
player2.attack(player1);
}
}

47
day01/src/logback.xml Normal file
View File

@@ -0,0 +1,47 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<!--
appender控制日志输出到哪里去
CONSOLE :表示当前的日志信息是可以输出到控制台的。
-->
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
<!--输出流对象 默认 System.out 改为 System.err-->
<target>System.out</target>
<encoder>
<!--格式化输出:%d表示日期%thread表示线程名%-5level级别从左显示5个字符宽度
%msg日志消息%n是换行符-->
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%-5level] %c [%thread] : %msg%n</pattern>
</encoder>
</appender>
<!-- File是输出的方向通向文件的 -->
<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
<charset>utf-8</charset>
</encoder>
<!--日志输出路径-->
<file>D:/log/inmind-data.log</file>
<!--指定日志文件拆分和压缩规则-->
<rollingPolicy
class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<!--通过指定压缩文件名称,来确定分割文件方式-->
<fileNamePattern>D:/log/inmind-data-%i-%d{yyyy-MM-dd}-.log.gz</fileNamePattern>
<!--文件拆分大小-->
<maxFileSize>1MB</maxFileSize>
</rollingPolicy>
</appender>
<!--
1、控制日志的输出情况开启日志取消日志
ALL全部打开
OFF表示关闭
-->
<!-- <root level="debug">-->
<!-- <root level="OFF">-->
<root level="error">
<appender-ref ref="CONSOLE"/>
<appender-ref ref="FILE" />
</root>
</configuration>