java - 如何将有效输入添加到数组列表中?

标签 java validation

这是我的 ID 程序,其中存储名字、姓氏、出生日期和地点、电子邮件和电话号码。如何制作和存储仅包含有效出生日期、电子邮件和电话号码(而不是具有所有属性)的人员对象?

这是我的主要 ID 程序:

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ID {
static List<Oseba> id = new ArrayList<Oseba>();

public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);
    int max = 0;
    int choice = 0;
    boolean isDate = false;

    String regEx_Email = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
    String regEx_Date = "(0?[1-9]|[12][0-9]|3[01])/(0?[1-9]|1[012])/((19|20)\\d\\d)";

    System.out.println("How many IDs would you like to enter? ");
    max = sc.nextInt();

    System.out.println(" 0. Exit. ");
    System.out.println(" 1. Add contact. ");
    System.out.println(" 2. Outprint all contacts. ");
    choice = sc.nextInt();

    while (choice != 0) {

        switch (choice) {
        case 0:
            System.out.println("Goodbye!");
            System.exit(0);

        case 1:
            while (choice != 2) {
                System.out.println("Enter First Name: ");
                String firstName = sc.next();

                System.out.println("Enter Last Name: ");
                String lastName = sc.next();

                System.out.println("Enter date of birth (dd-mm-yyyy): ");
                String date = sc.next();
                isDate = date.matches(regEx_Date);

                System.out.println("Enter place of birth: ");
                String place = sc.next();

                System.out.println("Enter email: ");
                String email = sc.next();

                Pattern p = Pattern.compile(regEx_Email);
                Matcher m = p.matcher(email);

                if (m.find()) {
                    System.out.println(email + " is a valid email address.");
                } else {
                    System.out.println(email + " is a invalid email address");
                }

                System.out.println("Enter phone number:");
                String phone = sc.next();

                addID(firstName, lastName, date, place, email, phone);
            }
            break;

        case 2:
            System.out.println("\n" + ID.id);
            break;

        default:
            System.out.println("Try again.");
            break;
        }
        System.out.println(" 0. Exit. ");
        System.out.println(" 1. Add contact. ");
        System.out.println(" 2. Outprint all contacts. ");
        choice = sc.nextInt();
    }
}

private static void addID(String firstName, String lastName, String date, String place, String email, String phone) {
    Person p = new Person(firstName, lastName, date, place, email, phone);
    id.add(p);
}


}

还有我的 Person 类:

class Person {
  String firstName;
  String lastName;
  String date;
  String place;
  String email;
  String phone;

public Person(String firstName, String lastName, String date, String place, String email, String phone) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.date = date;
    this.place = place;
    this.email = email;
    this.phone = phone;
}

public String getFirstName() {
    return firstName;
}

public void setFirstName(String firstName) {
    this.firstName = firstName;
}

public String getLastName() {
    return lastName;
}

public void setLastName(String lastName) {
    this.lastName = lastName;
}

public String getPlace() {
    return place;
}

public void setPlace(String place) {
    this.place = place;
}

public String getEmail() {
    return email;
}

public void setEmail(String email) {
    this.email = email;
}

public String getDate() {
    return date;
}

public void setDate(String date) {
    this.date = date;
}

public String getPhone() {
    return phone;
}

public void setPhone(String phone) {
    this.phone = phone;
}

public String toString() {
    return "First Name: " + firstName + "\n"
            + "Last Name: " + lastName + "\n"
            + "Date of birth: " + date + "\n" 
            + "Place of birth: "    + place + "\n" 
            + "Email: " + email + "\n"
            + "Phone number: " + phone + "\n\n";
}

}

感谢您的帮助。

最佳答案

最好的方法是将您的问题分解为更小的问题。例如,为了验证输入,您必须创建一个方法来负责验证每个案例的输入,而不是直接调用 setter。尝试在任何地方使用这种方法,因为低耦合和高内聚始终是一个要求!我将提供一个关于您的实现的示例,但是,有多种方法可以做到这一点。另外,我不会使用异常,因为我注意到您仍处于起步阶段。

除此之外,为了使其工作,您应该在 Person 类中添加一个默认构造函数(值是预先定义的)。

最后,尽管不建议使用多个 while 循环的方法,因为它会使代码变得更加复杂,但我使用它是为了向您演示如何确保获得正确的输入,例如,如果用户输入如果没有得到验证,那么程序将继续询问用户,直到获得正确的输入。此外,当用户犯错误时,应提供指示以指导他/她。 (这通常是在有异常(exception)的情况下完成的,在我们的例子中,尽管我们提供了简单的控制台打印)。

让我们看看:

public class ID {
static List<Oseba> id = new ArrayList<Oseba>();
\*we create the menu like that in order to avoid multiple lines repetitions *\
private static String menuOptions = "Menu:" + "\nExit - Insert 0"
            + "\nAdd contact - Insert 1" + "\nExit Outprint all contacts - Insert 2";

public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);
    int max = 0;
    int choice = 0;
    boolean isDate = false;

    System.out.println("How many IDs would you like to enter? ");
    max = sc.nextInt();
    Person p = new Person();

    while (true) {
        print(menuOptions);
        choice = sc.nextInt();
        switch (choice) {
        case 0:
            System.out.println("Goodbye!");
            System.exit(0);

        case 1:
                while(true){
                    String fname = getString("Enter First Name: ");
                    if(verifyName(fname)){
                        p.setFirstName(fname);
                        break;
                    }
                }
                while(true){
                    String lname = getString("Enter Last Name: ");
                    if(verifyName(lname)){
                        p.setLastName(lname);
                        break;
                    }
                }
                while(true){
                    String date = getString("Enter date of birth (dd-mm-yyyy): ");
                    if(verifyBirthDate(date)){
                        p.setDate(date);
                        break;
                    }
                }
                while(true){
                    String birthPlace = getString("Enter place of birth: ");
                    if(verifyBirthPlace(birthPlace)){
                        p.setPlace(birthPlace);
                        break;
                    }
                }
                while(true){
                    String email = getString("Enter email address: ");
                    if(verifyEmail(email)){
                        p.setEmail(email);
                        break;
                    }
                }
                while(true){
                    String phoneNumber = getString("Enter phone number: ");
                    if(verifyPhoneNumber(phoneNumber)){
                        p.setPhone(phoneNumber);
                        break;
                    }
                }
                addID(p);
            break;

        case 2:
            System.out.println("\n" + ID.id);
            break;

        default:
            System.out.println("Try again.");
            break;
        }
        print(menuOptions);
        choice = sc.nextInt();
    }
}

    private static void addID(Person prs) {
      id.add(prs);
    }

   public static Boolean verifyName(String name) {
        if(!name.matches("[a-zA-Z]+")){
            print("\nERROR_MESSAGE:____________The first/last name should contain only letters, everything else is not valid!");
            return false;
        }else{
            return true;
        }
    }

    public static Boolean verifyBirthDate(String date) {
        String regEx_Date = "(0?[1-9]|[12][0-9]|3[01])/(0?[1-9]|1[012])/((19|20)\\d\\d)";
        if(!date.matches(regEx_Date)){
            print("\nERROR_MESSAGE:____________The birth date is not valid!");
            return false;
        }else{
            return true;
        }
    }

    public static Boolean verifyBirthPlace(String birthPlace) {
        if(!birthPlace.matches("[a-zA-Z]+")){
            print("\nERROR_MESSAGE:____________The birth place is not valid!");
            return false;
        }else{
            return true;
        }
    }


    public static Boolean verifyEmail(String email) {
        String regEx_Email = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
        Pattern p = Pattern.compile(regEx_Email);
        Matcher m = p.matcher(email);
        if(!m.find()){
            print("\nERROR_MESSAGE:____________"+email+" is an invalid email address");
            return false;
        }else{
            return true;
        }
    }

    public static Boolean verifyPhoneNumber(String phoneNumber) {
        if(!phoneNumber.matches("[0-9]+")){
            print("\nERROR_MESSAGE:____________The phone No. should contain only numbers, everything else is not valid!");
            return false;
        }else{
            return true;
        }
    }

    public static String getString(String msg) {
        Scanner in = new Scanner(System.in);
        print(msg);
        String s = in.nextLine();
        return s;
    }

    public static void print(String s) {
        System.out.println(s);
    }


}

关于java - 如何将有效输入添加到数组列表中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20888601/

相关文章:

java.lang.NoSuchMethodError : org. hsqldb.DatabaseURL.parseURL maven运行时

java - 无法显示Json数据

java - 比较两个 CSV 文件并获取数据

Java 从命令行调用列表文件

asp.net - 如何在 .Net 中测试字符串(网页)的标记有效性?

php - 插入数据时如何使用mysql验证字符串

java - 如何在 Java 中修剪不间断的空间?

java - 如何检查(字符串)位置是否是 Java 中的有效保存路径?

javascript - 验证函数后返回 'true'

validation - 为什么添加 dropout 层对验证集有效,但对测试集无效?