mirror of
https://github.com/Dichgrem/Java.git
synced 2026-02-05 02:51:57 -05:00
update:demo7
This commit is contained in:
72
com/study/demo7/UserServiceMain.java
Normal file
72
com/study/demo7/UserServiceMain.java
Normal file
@@ -0,0 +1,72 @@
|
||||
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());
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user