import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

public class AddEmployee {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (true) {
            try {
                System.out.println("请输入员工信息,格式如下:");
                String input = sc.nextLine();
                String[] info = input.split(",");
                //验证用户名
                if (info[0].length() < 1 || info[0].length() > 20 || !info[0].matches("[a-zA-Z]+")) {
                    throw new Exception("用户名不符合要求,请重新输入!");
                }
                //验证年龄
                int age = Integer.parseInt(info[1]);
                if (age < 0 || age > 100) {
                    throw new Exception("年龄不符合要求,请重新输入!");
                }
                //验证性别
                if (!info[2].equals("男") && !info[2].equals("女")) {
                    throw new Exception("性别不符合要求,请重新输入!");
                }
                //将员工信息添加到文件中
                BufferedWriter writer = new BufferedWriter(new FileWriter("emp.txt", true));
                writer.write(input + "\n");
                writer.close();
                System.out.println("添加成功!");
                break;
            } catch (IOException e) {
                System.out.println("文件操作异常:" + e.getMessage());
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
        }
    }
}
Java 添加员工信息到文件:使用异常捕获机制进行输入验证

原文地址: https://www.cveoy.top/t/topic/oH9y 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录