0

I need to add in validation for when a user is adding a person to the ArrayList. That a first and last name is entered, address, legal state abbreviation. Etc. How to do I go about this?

I imagine an IF statement, but I am not sure how to incorporate that into the newFriend.setAddress(sc.nextLine()); type of line.

import java.util.*;
import java.io.*;
import javax.swing.*;


public class testAddressBook {

    //Personal Friend Array
    public static PersonalFriend newFriend = new PersonalFriend(null, null, null, null, null, null, null, null, null, null,0,null);
    public static ArrayList<PersonalFriend> FriendList = new ArrayList<PersonalFriend>();

    //Business Associate Array
    public static BusinessAssociate newBusiness = new BusinessAssociate(null, null, null, null,null, null, null, null,null, null, null, null);
    public static ArrayList<BusinessAssociate> salaryList = new ArrayList<BusinessAssociate>();


    public static ArrayList<Person> addressBook = new ArrayList<Person>();
    private static Scanner sc = new Scanner(System.in);
    private static char choice;
    private static char type;


    public static void main(String[] args) throws IOException {

        boolean switcher = true;
        do {
            System.out.println("\n\tAddress Book Menu");
            System.out.println("\n\t\tEnter A to (A)dd Person ");
            System.out.println("\t\tEnter R to (R)emove Person");
            System.out.println("\t\tEnter M to (M)odify Entry");
            System.out.println("\t\tEnter S to (S)earch Address Book ");
            System.out.println("\t\tEnter L to (L)ist ALL (sorted) ");
            System.out.println("\t\tEnter D to (D)ownload to Disk ");
            System.out.println("\t\tEnter U to (U)pload from Disk ");
            System.out.println("\t\tEnter P to (P)rint Address Book ");
            System.out.println("\t\tEnter Q to Quit");
            System.out.print("\n\tPlease enter your choice: ");
            choice = sc.nextLine().toUpperCase().charAt(0);


            while ((choice != 'A') && (choice != 'R') && (choice != 'M')  && (choice != 'S') && (choice != 'L')&& (choice != 'D')&& (choice != 'U')&& (choice != 'P')&&(choice != 'Q')) {
                System.out.println("Invalid choice!  Please select (A)dd, (D)elete, (M)odify, (S)earch, (L)ist or (Q)uit: ");
                choice = sc.nextLine().toUpperCase().charAt(0);
            }


            switch (choice) {
            case 'A' :      
                if (choice == 'A') {
                    System.out.print("\nAdd a (F)riend or (B)usiness Associate? ");
                    type = sc.nextLine().toUpperCase().charAt(0);

                    while ((type != 'F') && (type != 'B')) {
                        System.out.print("Invalid choice!  Please select (F)riend or (B)usiness Associate: ");
                        type = sc.nextLine().toUpperCase().charAt(0);
                    }


                    if (type == 'F') {

                        addPersonFriend();

                    }

                    else if (type == 'B') {
                        addBusinessPerson();
                    }
                }


                break;

            case 'R' :
                deletePerson();
                break;

            case 'M' :
                modifyPerson();
                break;

            case 'S' :

                searchPerson();

                break;

            case 'L' :
                listPerson();
                break;

            case 'D' :
                downloadDisk();
                break;

            case 'U' :
                uploadDisk();
                break;

            case 'P' :
                printAddressBook();
                break;

            case 'Q' :
                switcher = false;

                break;


            }


        }
        while (switcher != false);
        System.out.println("Session Over");

    }


    private static void addPersonFriend() {
        System.out.println("\nFollow the prompts.");
        newFriend = new PersonalFriend(null, null, null, null, null, null, null, null, null, null,0,null);
        System.out.print("\nEnter First Name: ");
        newFriend.setfName(sc.nextLine());
        System.out.print("Enter Last Name: ");
        newFriend.setlName(sc.nextLine());
        System.out.print("Enter Address: ");
        newFriend.setAddress(sc.nextLine());
        System.out.print("Enter City: ");
        newFriend.setCity(sc.nextLine());
        System.out.print("Enter State: ");
        newFriend.setState(sc.nextLine());
        System.out.print("Enter Zip: ");
        newFriend.setZip(sc.nextLine());
        System.out.print("Enter Phone Number: ");
        newFriend.setPhone(sc.nextLine());
        System.out.print("Enter Cell Phone Number: ");
        newFriend.setCellphone(sc.nextLine());
        System.out.print("Enter Email Number: ");
        newFriend.setEmail(sc.nextLine());
        System.out.print("Enter Birthday: ");
        newFriend.setBirthday(sc.nextLine());
        System.out.print("Enter Age: ");
        newFriend.setAge(sc.nextInt());
        System.out.print("Enter Zodiac: ");
        newFriend.setZodiac(sc.nextLine());
        System.out.print(" ");
        newFriend.setZodiac(sc.nextLine());
        addressBook.add(newFriend);

        System.out.println("\nYou have successfully added a new person!");
    }

    private static void addBusinessPerson() {
        System.out.println("\nFollow the prompts.");
        newBusiness = new BusinessAssociate(null, null, null, null, null, null, null, null, null, null, null, null);
        System.out.print("\nEnter First Name: ");
        newBusiness.setfName(sc.nextLine());
        System.out.print("Enter Last Name: ");
        newBusiness.setlName(sc.nextLine());
        System.out.print("Enter Address: ");
        newBusiness.setAddress(sc.nextLine());
        System.out.print("Enter City: ");
        newBusiness.setCity(sc.nextLine());
        System.out.print("Enter State: ");
        newBusiness.setState(sc.nextLine());
        System.out.print("Enter Zip: ");
        newBusiness.setZip(sc.nextLine());
        System.out.print("Enter Phone Number: ");
        newBusiness.setPhone(sc.nextLine());
        System.out.print("Enter Cell Phone Number: ");
        newBusiness.setCellphone(sc.nextLine());
        System.out.print("Enter Email Number: ");
        newBusiness.setEmail(sc.nextLine());
        System.out.print("Enter Job Title: ");
        newBusiness.setJobtitle(sc.nextLine());
        System.out.print("Enter Fax Number: ");
        newBusiness.setFax(sc.nextLine());
        System.out.print("Enter Company Name: ");
        newBusiness.setCompany(sc.nextLine());      
        addressBook.add(newBusiness);

        System.out.println("\nYou have successfully added a new person!");
    }

    private static void deletePerson() {
        System.out.println("Enter first name of person: ");
        String deleteName = sc.nextLine();

        boolean foundMod = false;
        int index2 = 0;

        while (index2 < addressBook.size() && !foundMod) {
            if ( ((Person)addressBook.get(index2)).getfName().equalsIgnoreCase(deleteName)) {
                foundMod = true;
                addressBook.remove(index2);

                System.out.println("\nYou have successfully deleted this person.");
            }

            else {
                index2++;
            }

            if (foundMod)
            {}
            else
                System.out.println("Unknown");
        }

    }

    private static void modifyPerson() {

        newBusiness = new BusinessAssociate(null, null, null, null, null, null, null, null, null, null, null, null);
        newFriend = new PersonalFriend(null, null, null, null, null, null, null, null, null, null,0,null);


        System.out.print("Enter first name of person: ");
        sc.nextLine();



        if (newBusiness instanceof BusinessAssociate) {
            System.out.println("Change this business listing:  ");
            addBusinessPerson();
        }

        if (newFriend instanceof PersonalFriend) {
            System.out.println("This is a Personal Friend:  ");
            addPersonFriend();
        }


    }



    private static void searchPerson() {

        System.out.println("Enter first name of person: ");
        String findName = sc.nextLine();

        boolean found = false;
        int index = 0;

        while (index < addressBook.size() && !found) {
            if ( ((Person)addressBook.get(index)).getfName().equalsIgnoreCase(findName)) {
                found = true;
            }

            else {
                index++;
            }

            if (found)
                System.out.println("Found: " + addressBook.get(index));
            else{}

        }


    }

    private static void listPerson() {
        System.out.println("\nThere are " + addressBook.size() + " people in this address book.\n");
        Collections.sort(addressBook);


        for (int i = 0; i < addressBook.size(); i++) {
            System.out.println(addressBook.get(i));


        }
        System.out.println();



    }


    public static void downloadDisk() { 
        File file = new File("addressBookContents.dtd");


        // Create a file
        PrintWriter output = null;
        try {
            output = new PrintWriter(file);
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        // Write formatted output to the file
        output.println(addressBook);
        System.out.println("\nSaved to disk in the default folder for this program. \n");

        // Close the file
        output.close();

    }

    private static void uploadDisk() throws IOException {

        JFileChooser fileChooser = new JFileChooser();
        if (fileChooser.showOpenDialog(null)
                == JFileChooser.APPROVE_OPTION) {
            // Get the selected file
            java.io.File file = fileChooser.getSelectedFile();

            // Create a Scanner for the file
            Scanner input = new Scanner(file);

            // Read text from the file
            while (input.hasNext()) {
                System.out.println(input.nextLine());
            }

            // Close the file
            input.close();
        }
        else {
            System.out.println("No file selected");
        }


    }


    @SuppressWarnings("unchecked")
    private static void printAddressBook() {

        File file = new File("addressBookContents.txt");


        // Create a file
        PrintWriter output = null;
        try {
            output = new PrintWriter(file);
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        // Write formatted output to the file
        output.println(addressBook);
        System.out.println("\nPrinting Successful! \n");

        // Close the file
        output.close();

    }


}//ends class

4 Answers 4

1

A good way to ensure that an object is valid is to make it immutable and check in its constructor that all inputs are as you want.

The complication here is that you're getting lots of information in separate steps. You could store each in a variable, before calling a constructor with a lot of arguments, but that's a little hard to read. Instead consider the builder pattern

Sign up to request clarification or add additional context in comments.

Comments

1

I am not quite sure about which one is your objective. I think you could have 2 validations:

  • validate whatever you need at the moment to assign the instance to the list asserting that it has all the attributes already set.
  • validate the value being set to the instance.

1st case: you could create a method which validate that all the properties has a valid value. And use it with if it is valid then add it to the list.

2nd case: in the set method of each attribute to validate and only assign the value if it is valid .

you might want to implement your own implementation of arraylist where you override the add method to insert there the validation, so there is no other way to use that specific arraylist.

Comments

0

You cannot do a validation when you reading. You can use something piece of code like follows to do the validation and ask the user to enter a valid answer until user gives a matched value.

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);
        String name = get("First Name", "\\D+", scanner);

    }

    public static String get(String field, String regEx, Scanner scanner) {
        while (true) {
            System.out.println("Enter " + field + " :");
            String str = scanner.nextLine();
            if (str.matches(regEx)) {
                return str;
            }
            System.out.println("Please enter a correct " + field);
        }
    }

Here I am validating whether the first name consists of alpha numeric characters. Otherwise it will ask the user to enter the field again. Eg. Eranda2 - fail, Eranda - success

Comments

0

use while (true) { ... } to achieve this. for example,

while (true)
{
    *Your code that will ask user to enter a value for address field.*
    *assign the entered value to the address field*
    *This loop will continue until correct value is received and assigned.*
}

The while loop will keep prompting the user to enter the address until correct entry is not received. Try to understand it with integer values and then move to String etc. because it is easy to understand what the loop will do in case you enter non-integer values.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.