七、常用工具类
7.1 字符串处理
public class StringDemo {
public static void main(String[] args) {
String str = "Hello, Java!";
// 常用方法
System.out.println(str.length()); // 长度
System.out.println(str.charAt(0)); // 获取字符
System.out.println(str.indexOf("Java")); // 查找位置
System.out.println(str.substring(7)); // 截取子串
System.out.println(str.substring(7, 11)); // 截取区间
System.out.println(str.toLowerCase()); // 转小写
System.out.println(str.toUpperCase()); // 转大写
System.out.println(str.replace("Java", "World")); // 替换
System.out.println(str.startsWith("Hello")); // 判断开头
System.out.println(str.endsWith("!")); // 判断结尾
System.out.println(str.contains("Java")); // 是否包含
// 字符串分割
String[] parts = "a,b,c".split(",");
// 去除空白
String withSpaces = " Hello ";
System.out.println(withSpaces.trim());
// 字符串比较
String s1 = "hello";
String s2 = "hello";
System.out.println(s1.equals(s2)); // 内容比较
System.out.println(s1 == s2); // 引用比较(不推荐)
// StringBuilder:可变字符串
StringBuilder sb = new StringBuilder();
sb.append("Hello");
sb.append(" ");
sb.append("World");
System.out.println(sb.toString());
// 字符串拼接性能
// 慢:使用+拼接大量字符串
// 快:使用StringBuilder
}
}
7.2 集合框架
import java.util.*;
public class CollectionDemo {
public static void main(String[] args) {
// List:有序可重复
List<String> list = new ArrayList<>();
list.add("苹果");
list.add("香蕉");
list.add("苹果");
System.out.println(list.get(0)); // 获取
System.out.println(list.size()); // 大小
for (String item : list) {
System.out.println(item);
}
// Set:无序不重复
Set<String> set = new HashSet<>();
set.add("苹果");
set.add("香蕉");
set.add("苹果"); // 不会重复添加
System.out.println(set.size()); // 2
// Map:键值对
Map<String, Integer> map = new HashMap<>();
map.put("苹果", 5);
map.put("香蕉", 3);
map.put("橙子", 4);
System.out.println(map.get("苹果")); // 5
System.out.println(map.containsKey("香蕉")); // true
// 遍历Map
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
// 集合工具类
Collections.sort(list); // 排序
Collections.reverse(list); // 反转
Collections.shuffle(list); // 随机打乱
}
}
7.3 日期时间API
import java.time.*;
import java.time.format.DateTimeFormatter;
public class DateTimeDemo {
public static void main(String[] args) {
// 当前日期时间
LocalDate date = LocalDate.now();
LocalTime time = LocalTime.now();
LocalDateTime dateTime = LocalDateTime.now();
System.out.println(date); // 2024-01-15
System.out.println(time); // 14:30:25.123
System.out.println(dateTime); // 2024-01-15T14:30:25.123
// 创建指定日期
LocalDate birth = LocalDate.of(2000, 1, 1);
// 日期计算
LocalDate tomorrow = date.plusDays(1);
LocalDate nextMonth = date.plusMonths(1);
LocalDate lastYear = date.minusYears(1);
// 比较日期
System.out.println(date.isAfter(birth)); // true
System.out.println(date.isBefore(birth)); // false
// 格式化
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String formatted = dateTime.format(formatter);
System.out.println(formatted);
// 解析字符串
LocalDate parsed = LocalDate.parse("2024-01-15");
}
}
八、异常处理
8.1 try-catch-finally
import java.io.*;
public class ExceptionDemo {
public static void main(String[] args) {
try {
// 可能抛出异常的代码
int result = divide(10, 0);
System.out.println("结果:" + result);
// 读取文件
FileReader file = new FileReader("test.txt");
BufferedReader reader = new BufferedReader(file);
String line = reader.readLine();
System.out.println(line);
reader.close();
} catch (ArithmeticException e) {
// 处理算术异常
System.out.println("算术异常:" + e.getMessage());
} catch (FileNotFoundException e) {
// 处理文件未找到异常
System.out.println("文件未找到:" + e.getMessage());
} catch (IOException e) {
// 处理IO异常
System.out.println("IO异常:" + e.getMessage());
} catch (Exception e) {
// 处理其他所有异常
System.out.println("其他异常:" + e.getMessage());
} finally {
// 无论是否异常都会执行
System.out.println("finally块执行");
}
}
public static int divide(int a, int b) {
if (b == 0) {
throw new ArithmeticException("除数不能为0");
}
return a / b;
}
}
8.2 自定义异常
// 自定义异常
class AgeException extends Exception {
public AgeException(String message) {
super(message);
}
}
public class CustomExceptionDemo {
public static void checkAge(int age) throws AgeException {
if (age < 0) {
throw new AgeException("年龄不能为负数");
}
if (age > 150) {
throw new AgeException("年龄不能超过150岁");
}
System.out.println("年龄有效:" + age);
}
public static void main(String[] args) {
try {
checkAge(200);
} catch (AgeException e) {
System.out.println("年龄验证失败:" + e.getMessage());
}
}
}
九、文件I/O
9.1 文件读写
import java.io.*;
import java.nio.file.*;
public class FileIODemo {
public static void main(String[] args) {
// 写入文件
try (BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt"))) {
writer.write("第一行");
writer.newLine();
writer.write("第二行");
writer.newLine();
System.out.println("写入成功");
} catch (IOException e) {
e.printStackTrace();
}
// 读取文件
try (BufferedReader reader = new BufferedReader(new FileReader("output.txt"))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
// NIO方式(Java 7+)
try {
// 写入
Files.write(Paths.get("nio_output.txt"), "Hello NIO".getBytes());
// 读取
byte[] data = Files.readAllBytes(Paths.get("nio_output.txt"));
System.out.println(new String(data));
} catch (IOException e) {
e.printStackTrace();
}
}
}
十、实战案例:学生成绩管理系统
import java.util.*;
public class StudentManager {
// 学生类
static class Student {
private int id;
private String name;
private Map<String, Double> scores;
public Student(int id, String name) {
this.id = id;
this.name = name;
this.scores = new HashMap<>();
}
public void addScore(String subject, double score) {
scores.put(subject, score);
}
public double getAverage() {
if (scores.isEmpty()) return 0;
double sum = 0;
for (double score : scores.values()) {
sum += score;
}
return sum / scores.size();
}
public void display() {
System.out.println("学号:" + id + ",姓名:" + name);
System.out.println("成绩:");
for (Map.Entry<String, Double> entry : scores.entrySet()) {
System.out.println(" " + entry.getKey() + ": " + entry.getValue());
}
System.out.println("平均分:" + String.format("%.2f", getAverage()));
System.out.println("------------------------");
}
// Getters
public int getId() { return id; }
public String getName() { return name; }
}
// 成绩管理系统
private Map<Integer, Student> students;
private Scanner scanner;
public StudentManager() {
students = new HashMap<>();
scanner = new Scanner(System.in);
}
public void addStudent() {
System.out.println("\n--- 添加学生 ---");
System.out.print("学号:");
int id = scanner.nextInt();
scanner.nextLine(); // 消耗换行符
System.out.print("姓名:");
String name = scanner.nextLine();
if (students.containsKey(id)) {
System.out.println("学号已存在!");
return;
}
Student student = new Student(id, name);
students.put(id, student);
System.out.println("学生添加成功!");
}
public void addScore() {
System.out.println("\n--- 添加成绩 ---");
System.out.print("学号:");
int id = scanner.nextInt();
scanner.nextLine();
Student student = students.get(id);
if (student == null) {
System.out.println("学生不存在!");
return;
}
System.out.print("科目:");
String subject = scanner.nextLine();
System.out.print("成绩:");
double score = scanner.nextDouble();
scanner.nextLine();
student.addScore(subject, score);
System.out.println("成绩添加成功!");
}
public void displayAll() {
System.out.println("\n--- 学生列表 ---");
if (students.isEmpty()) {
System.out.println("暂无学生数据");
return;
}
for (Student student : students.values()) {
student.display();
}
}
public void searchStudent() {
System.out.println("\n--- 搜索学生 ---");
System.out.print("学号:");
int id = scanner.nextInt();
scanner.nextLine();
Student student = students.get(id);
if (student == null) {
System.out.println("学生不存在!");
} else {
student.display();
}
}
public void deleteStudent() {
System.out.println("\n--- 删除学生 ---");
System.out.print("学号:");
int id = scanner.nextInt();
scanner.nextLine();
Student removed = students.remove(id);
if (removed != null) {
System.out.println("学生 " + removed.getName() + " 已删除");
} else {
System.out.println("学生不存在!");
}
}
public void showStatistics() {
System.out.println("\n--- 统计信息 ---");
if (students.isEmpty()) {
System.out.println("暂无学生数据");
return;
}
double total = 0;
double max = 0;
double min = 100;
Student bestStudent = null;
Student worstStudent = null;
for (Student student : students.values()) {
double avg = student.getAverage();
total += avg;
if (avg > max) {
max = avg;
bestStudent = student;
}
if (avg < min) {
min = avg;
worstStudent = student;
}
}
double classAvg = total / students.size();
System.out.println("班级人数:" + students.size());
System.out.println("班级平均分:" + String.format("%.2f", classAvg));
if (bestStudent != null) {
System.out.println("最高分:" + bestStudent.getName() + " (" +
String.format("%.2f", max) + "分)");
}
if (worstStudent != null) {
System.out.println("最低分:" + worstStudent.getName() + " (" +
String.format("%.2f", min) + "分)");
}
}
public void run() {
while (true) {
System.out.println("\n" + "=".repeat(40));
System.out.println("学生成绩管理系统");
System.out.println("=".repeat(40));
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("请选择操作(1-7):");
int choice = scanner.nextInt();
scanner.nextLine();
switch (choice) {
case 1:
addStudent();
break;
case 2:
addScore();
break;
case 3:
displayAll();
break;
case 4:
searchStudent();
break;
case 5:
deleteStudent();
break;
case 6:
showStatistics();
break;
case 7:
System.out.println("感谢使用学生成绩管理系统!");
return;
default:
System.out.println("无效选择,请重新输入");
}
}
}
public static void main(String[] args) {
StudentManager manager = new StudentManager();
manager.run();
}
}
对于初学者而言,最重要的是理解面向对象思想和坚持动手实践。不要停留在阅读文档,尽快创建你的第一个Java程序,然后逐步增加功能。随着一个个小项目的完成,你对Java的理解会越来越深入,编写代码也会越来越得心应手。
来源:
https://app-ac8abncezqpt.appmiaoda.com