user3023250
user3023250

Reputation: 61

How to add valid input into arraylist?

This is my ID program which stores first name, last name, date and place on birth, email and phone number. How do I make and store a person object with only valid birth date, email and phone number (instead of having all the attributes)?

This is my main ID program:

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);
}


}

And my Person class:

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";
}

}

Thanks for the help.

Upvotes: 2

Views: 1134

Answers (5)

nmargaritis
nmargaritis

Reputation: 879

The best approach would be to break down your problem into smaller ones. For example, in order to validate the input, what you will have to do, instead of calling the setter directly is to create a method that will be responsible to validate the input for every single case. Try to use this approach everywhere since low coupling and high cohesion is always a requirement! I will provide an example on your implementation, however, there are multiple ways to do that. Also I wont use exceptions since I noticed that you are still in the beginning.

Apart from that, in order for this to work, you should add a default constructor(the values are predifined) in the Person Class.

Finally, eventhough the approach with multiple while loops is not recommented because it makes the code more complicated, I used it in order to demonstrate you how you can make sure that you will get the correct input, for example if the user input doesnt get validated, then the program will continue to ask the user until it will get the correct input. Additionally, when the user makes a mistake, directions should be provided in order to guide him/her. (this is normally done with exceptions, in our case though we provide this with simple console prints).

So let's see:

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);
    }


}

Upvotes: 2

Anirban Pal
Anirban Pal

Reputation: 529

Add a new boolean variable to keep track valid inputs. If all inputs are valid then only add Person object to ArrayList

            boolean isValid=true;
            if (m.find()) {
                System.out.println(email + " is a valid email address.");
            } else {
                isValid=false;
                System.out.println(email + " is a invalid email address");
            }
            if(isValid)
            {
                //Do other check phone number and valid birth date similarly
            }
            if(isValid)
            {
            addID(firstName, lastName, date, place, email, phone);
            }

Upvotes: 0

Mik378
Mik378

Reputation: 22171

Have you ever heard about Primitive Obsession?

I would use a Date (JodaDate) instead of String for birth date.

I would create an Email value object, throwing an IllegalArgumentException if the String provided isn't a valid email (validated by regexp).

I would create a Phone value object, throwing an IllegalArgumentException if the String provided isn't a valid phone number.

The constructor becoming:

public Person(String firstName, String lastName, Date birthDate, String place, Email email, Phone phone)

For instance, the Email object would be:

public class Email {

    private String value;

    public Email(String email) {
      if(isNotValid(email))
        throw new IllegalArgumentException("Your mail is not valid!");
      this.value = email;
    }

    public final String getValue(){
      return email;
    } 

    private boolean isNotValid(){
       //return false if email regexp validation is not verified
    }

    //....equals - hashcode if needed here
}

Thus, your Person would always be a valid person. Indeed, checking that its components are valid is then the responsibility of the client, not the Person directly. It's more informative for the reader what a Person expects, just by reading the API.

Upvotes: 1

herry
herry

Reputation: 1738

May better name for isDate field is isValidDate.

Can you use simple if statement:

if(isValidDate && m.find())
   addID(firstName, lastName, date, place, email, phone);

Or can you create method for checking validation:

private boolean isValidDate(String date){
 if(number!=null && number!=""){
  String regEx_Date = "(0?[1-9]|[12][0-9]|3[01])/(0?[1-9]|1[012])/((19|20)\\d\\d)";
  return date.matches(regEx_Date);
}
return false;
}

Upvotes: 1

Anubian Noob
Anubian Noob

Reputation: 13596

Create a constructor like this

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

You could optionally add

this.firstName = null;
this.lastName = null;
//for all of your fields.

You also need to uodate your getters and toString method to check if the field has been initialized. For example, for your getFirstName()

if (firstName!=null)
    return firstName;
return "";

Upvotes: 1

Related Questions