mirror of
https://github.com/Dichgrem/Java.git
synced 2026-02-05 01:11:57 -05:00
73 lines
1.7 KiB
Java
73 lines
1.7 KiB
Java
package com.study.demo7;
|
|
|
|
import java.io.*;
|
|
|
|
// 自定义异常
|
|
class InvalidUserException extends Exception {
|
|
public InvalidUserException(String message) {
|
|
super(message);
|
|
}
|
|
}
|
|
|
|
// User 类
|
|
class User {
|
|
private String name;
|
|
private int age;
|
|
|
|
public User(String name, int age) {
|
|
this.name = name;
|
|
this.age = age;
|
|
}
|
|
|
|
public String getName() {
|
|
return name;
|
|
}
|
|
|
|
public int getAge() {
|
|
return age;
|
|
}
|
|
}
|
|
|
|
// 用户服务类
|
|
class UserService {
|
|
public void register(User user) throws InvalidUserException {
|
|
// 校验
|
|
if (user.getName() == null || user.getName().trim().isEmpty()) {
|
|
throw new InvalidUserException("用户名不能为空");
|
|
}
|
|
if (user.getAge() < 0) {
|
|
throw new InvalidUserException("年龄不能为负数");
|
|
}
|
|
|
|
// 写入文件
|
|
try (BufferedWriter writer = new BufferedWriter(new FileWriter("users.txt", true))) {
|
|
writer.write("姓名: " + user.getName() + ", 年龄: " + user.getAge());
|
|
writer.newLine();
|
|
System.out.println("用户注册成功,信息已保存");
|
|
} catch (IOException e) {
|
|
System.out.println("用户信息保存失败: " + e.getMessage());
|
|
}
|
|
}
|
|
}
|
|
|
|
// 主类
|
|
public class UserServiceMain {
|
|
public static void main(String[] args) {
|
|
UserService service = new UserService();
|
|
User user1 = new User("张三", 25);
|
|
User user2 = new User("李四", -1);
|
|
|
|
try {
|
|
service.register(user1);
|
|
} catch (InvalidUserException e) {
|
|
System.out.println("注册失败: " + e.getMessage());
|
|
}
|
|
|
|
try {
|
|
service.register(user2);
|
|
} catch (InvalidUserException e) {
|
|
System.out.println("注册失败: " + e.getMessage());
|
|
}
|
|
}
|
|
}
|