Member Avatar for TheStig01

Hi all,
So i basically created a database with an arraylsit. All the data is stored in the arraylist and is added by a stringLine.

All this is shown in the code

My Database is an Insurance Database.
Well basically i'm finding it hard to find out how to actually search for a Policy by Id number and when it is found it returns that policy

Here is the first class that stroes the variables, getters and setters, saving and loading methods.

import java.io.*;

public class Policy implements Serializable {

// variables to store Policy information
// Insurance Details
protected String policyno; //int
protected String typeofinsurance;
protected String ncbyears; //int
protected double discount; 
protected String claim;
protected String fault;

protected String psd;
protected String ped;
protected String DOB;

// Client Details
protected String id;
protected String name;
protected String surname;
protected String address;
protected String job;
protected String status;
protected String postcode;

// no argument constructor calls 6 argument constructor with default values
public Policy(){

}// end 0 argument constructor Book()

// begin six argument Book constructor
public Policy( String id, String DOB, String name, String surname, String address, String job, String status, String postcode, String policyno, String psd, String ped, String typeofinsurance, String ncbyears, double discount, String claim, String fault) //String sDsp, String sDep,
{

this.id= id;
this.DOB = DOB;
this.name = name;
this.surname = surname;
this.address = address;
this.job=job;
this.status= status;
this.postcode= postcode;
this.policyno = policyno;
this.psd = psd;
this.ped = ped;
this.typeofinsurance= typeofinsurance;
this.ncbyears= ncbyears;
this.discount = discount;
this.claim= claim;
this.fault =fault;

}

public String getPolicyno() {
        return policyno;
}

public void setPolicyno(String policyno) { //!!!!!! MUST BE INT
        this.policyno = policyno;
}

public String getPsd() {
        return psd;
}

public void setPsd(String psd) {
        this.psd = psd;
}

public String getPed() {
        return ped;
}

public void setPed(String ped) {
        this.ped = ped;
}

public String getDOB() {
        return DOB;
}

public void setDOB(String DOB) {
        this.DOB = DOB;
}
   
public String getTypeofinsurance() {
        return typeofinsurance;
}

public void setTypeofinsurance(String typeofinsurance) {
        this.typeofinsurance = typeofinsurance;
}

public String getNcbyears() { //!!!!!! MUST BE INT
        return ncbyears;
}

public void setNcbyears(String ncbyears) {
        this.ncbyears = ncbyears;
}

public double getDiscount() { //!!!!!! MUST BE DOUBLE
        return discount;
}

public void setDiscount(double discount) {
        this.discount = discount;
}

public String getClaim() {
        return claim;
}

public void setClaim(String claim) {
        this.claim = claim;
}

public String getFault() {
        return fault;
}

public void setFault(String fault) {
        this.fault = fault;
}

public String getId() {
        return id;
}

public void setId(String id) {
        this.id = id;
}

public String getName() {
        return name;
}

public void setName(String name) {
        this.name = name;
}

public String getSurname() {
        return surname;
}

public void setSurname(String surname) {
        this.surname = surname;
}

public String getAddress() {
        return address;
}

public void setAddress(String address) {
        this.address = address;
}

public String getJob() {
        return job;
}

public void setJob(String job) {
        this.job = job;
}

public String getStatus() {
        return status;
}

public void setStatus(String status) {
        this.status = status;
}

public String getPostcode() {
        return postcode;
}

public void setPostcode(String postcode) {
        this.postcode = postcode;
}

private void writeObject(java.io.ObjectOutputStream out) throws IOException  {        
        out.writeObject(policyno);
        out.writeObject(typeofinsurance);
        out.writeObject(ncbyears);
        out.writeObject(discount);
        out.writeObject(claim);
        out.writeObject(fault);
}

private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException {
        policyno = (String)in.readObject();
        typeofinsurance = (String)in.readObject();
        ncbyears = (String)in.readObject();
        discount = (Double)in.readObject();
        claim = (String)in.readObject();
        fault = (String)in.readObject();
}

private void readObjectNoData() throws ObjectStreamException{}
}

// end six argument Book constructor

This is the Second class that includes adding a policy, deleting and SEARCHING BY INDEX NUMBER ( but i am required to also search by ID Number)

import java.util.*;
import java.io.*;
import java.util.Date; 
import java.util.Calendar;             
import java.text.SimpleDateFormat; 
import java.text.ParseException;

public class PolicyTable extends Policy {

//Save Database File in a Binary File 
private final String POLICYFILE = "policy.dat";

//Validation Variable and boolean
boolean Validation;

//Arraylist and Scanner
ArrayList PolicyInfo = new ArrayList();
Scanner userInput = new Scanner(System.in);

//Default Contructor to load all policies
public PolicyTable() {

loadPoliciesFromFile();
}

// Add new Policies
public void addPolicyRecord()throws IOException {

        // variable to hold all 6 book entries into one final string
        String stringLine;
        
        //Due to validation techniques and complicaitons in jumping this must be done using methods
        enterIdNumber();
               
        enterName();
        
        enterSurname();
       
        enterAddress();
        
        enterJob();
        
        enterDob();
                
        enterStatus();
        
        enterPostcode();
        
        enterPolicyno();
        
        enterPsd();
        
        enterPed();
        
        enterTypeofinsurance();
        
        enterNcbyears();
        
        enterDiscount();
        
        enterClaim();   
        
        enterFault();
             
// adds all user input values and creates one single String line
stringLine = "ID      : " + getId() + " \nNAME    : " + getName() + " \nSURNAME : " + getSurname() + " \nADDRESS : " + getAddress() + "\nDate Of Birth : " + getDOB() + " \nJOB     : " + getJob() + " \nSTATUS  : " + getStatus() + " \nPOSTCODE: " + getPostcode() + " \nPOLICY NUMBER     : " + getPolicyno() + "\nPolicy Initiation Date : " + getPsd() + "\nPolicy Expirary Date : " + getPed() + " \nTYPE OF INSURANCE : " + getTypeofinsurance() + " \nNCB YEARS         : " + getNcbyears() + " \nDISCOUNT    : " + getDiscount() + "%\nCLAIM(YES/NO)     : " + getClaim() + " \nFAULT CODE        : " + getFault() + " \n";

// adds the new line of text to the arrayList
PolicyInfo.add(stringLine);
savePoliciesToFile();

}

//====================================================================================================//
//========================PRINT POLICIES AND AMOUNT OF POLICIES IN DATABASE===========================//
//====================================================================================================//

public void printTotal(){

        // prints the toal amount of objects within the ArrayList
        System.out.print("\nTotal Number of Policies : " + PolicyInfo.size() + "\n");
        System.out.print("\n");
}


public void printPolices(){

       
        Iterator itr = PolicyInfo.iterator();
        while(itr.hasNext())
        System.out.println(itr.next());
        System.out.println();
}

//====================================================================================================//
//====================================SEARCH FOR POLICIES=============================================//
//====================================================================================================//

public void searchIndex(){
        int userIndex;
        
        Scanner scanner = new Scanner(System.in);
        
        System.out.println("Please enter the index number you wish to search");
        userIndex = scanner.nextInt();
        
        System.out.println(PolicyInfo.get(userIndex));
        System.out.print("\n");
}

//====================================================================================================//
//================================FORMAT AND DELETE A SPECIFIC POLICY=================================//
//====================================================================================================//

public void formatDatabase() {
        Scanner scanner = new Scanner(System.in);
        
        System.out.print("Format Database [Y] or [N] ? : ");
        String s = scanner.next();
                    
        if ((s.equals("Y")) || (s.equals("y"))) {
        PolicyInfo.clear();
        savePoliciesToFile();

        System.out.println ("\nDatabase has been formatted" );
        
}
}
            
public void deleteRecord() {
        int userIndex;
        Scanner scanner = new Scanner(System.in);
        System.out.println("Please enter the index number you to delete");
        userIndex = scanner.nextInt();
        System.out.println(" Policy " + userIndex + " is removed " + PolicyInfo.remove( userIndex ) + "\n");
        
        savePoliciesToFile();

}

//====================================================================================================//
//========================SAVE AND LOADDATABASE POLICIES TO AND FROM BINARY FILE======================//
//====================================================================================================//

private void loadPoliciesFromFile() {
        PolicyInfo.clear();
        
        FileInputStream f_in;
        try
        {
            f_in = new FileInputStream(POLICYFILE);
            ObjectInputStream obj_in = new ObjectInputStream(f_in);
            Object obj = obj_in.readObject();
            PolicyInfo = (ArrayList)obj;
        }
        catch (IOException e){}
        catch (ClassNotFoundException e){}
}

private void savePoliciesToFile()  {
        FileOutputStream f_out;
        try
        {
            f_out = new FileOutputStream(POLICYFILE);
            ObjectOutputStream obj_out = new ObjectOutputStream(f_out);
            obj_out.writeObject(PolicyInfo);
        }
        catch (IOException e){}
}

//====================================================================================================//
//==================================VALIDATION AND INPUT DATA METHODS=================================//
//====================================================================================================//

private void enterIdNumber() {
                   
        do
        {
            System.out.println("\nPlease enter the Policy Holder ID Number");
            id = userInput.next(); 
            
            
            Validation = checkIDnuber(id);

            if (Validation == false)
            {
                System.out.println("ENTER A VALID Policy Holder ID Number in the form [12345] [M]");
            }
        }
        while (Validation == false);

        setId(id);
}

public static boolean checkIDnuber(String id)
     {
       return id.matches( "[0-9][0-9][0-9][0-9][0-9][MA]*" );
}

//---------------------------------------------------------------------------------------------------------------

private void enterName() {
         
        do
        {
            System.out.println("\nPlease enter the Policy Holder Name");
            name = userInput.next();
                        
            Validation = checkName(name);

            if (Validation == false)
            {
                System.out.println("ENTER A VALID Policy Holder Name");
            }
        }
        while (Validation == false);

        setName(name);
}

public static boolean checkName(String name)
     {
       return name.matches( "[A-z][a-zA-z]*" );
}

//--------------------------------------------------------------------------------------------------------------

private void enterSurname() {
            
        do
        {
            System.out.println("\nPlease enter the Policy Holder Surname");
            surname = userInput.next();
            
            
            Validation = checkSurname(surname);

            if (Validation == false)
            {
                System.out.println("ENTER A VALID Policy Holder Surname");
            }
        }
        while (Validation == false);

        setSurname(surname);
}

public static boolean checkSurname(String surname)
     {
       return surname.matches( "[a-zA-z]+([ '-][a-zA-Z]+)*"  );
}

//--------------------------------------------------------------------------------------------------------------

private void enterAddress() { 
            
        do
        {
            System.out.println("\nPlease enter the Policy Holder Address in the form [123] [Street Name]");
            address = userInput.next();
            
            
            Validation = checkAddress(address);

            if (Validation == false)
            {
                System.out.println("ENTER A VALID Policy Holder Address");
            }
        }
        while (Validation == false);

        setAddress(address);
}

public static boolean checkAddress(String address)
     {
       return address.matches("[a-zA-z]+([ '-][a-zA-Z]+)*");
}

//--------------------------------------------------------------------------------------------------------------

private void enterJob() {
            
        do
        {
            System.out.println("\nPlease enter the Policy Holder Job");
            job = userInput.next();
            
            
            Validation = checkJob(job);

            if (Validation == false)
            {
                System.out.println("ENTER A VALID Policy Holder Job");
            }
        }
        while (Validation == false);

        setJob(job);
}

public static boolean checkJob(String job)
     {
       return job.matches("[a-zA-z]+([ '-][a-zA-Z]+)*" );
}

//--------------------------------------------------------------------------------------------------------------

private void enterStatus() {
        
       int choice;
       
       System.out.println("\nPlease enter your Status [1] Single [2] Married");
            choice = userInput.nextInt();
            
       if ( choice == 1 ) 
           status = "Single";
           else 
           if (choice == 2) 
               status = "Married";
                 else 
                        System.out.println ("Invalid Input");
    
        setStatus(status);
}

//--------------------------------------------------------------------------------------------------------------

private void enterPostcode() { 
            
        do
        {
            System.out.println("\nPlease enter the Policy Holder Postcode");
            postcode = userInput.next();
                                              
            Validation = checkPostcode(postcode);

            if (Validation == false)
            {
                System.out.println("ENTER A VALID Policy Holder Postcode");
            }
        }
        while (Validation == false);

        setPostcode(postcode);
}

public static boolean checkPostcode(String postcode)
     {
       return postcode.matches("[A-z][A-z][A-z]\\d\\d\\d\\d" );
}

//--------------------------------------------------------------------------------------------------------------

private void enterPolicyno() { 
            
        do
        {
            System.out.println("\nPlease enter the Policy Number");
            policyno = userInput.next();
             
            Validation = checkPolicyno(policyno);

            if (Validation == false)
            {
                System.out.println("ENTER A VALID Policy Number");
            }
        }
        while (Validation == false);

        setPolicyno(policyno);
}

public static boolean checkPolicyno( String policyno)
     {
       return policyno.matches("[0-9]*" );
}

//--------------------------------------------------------------------------------------------------------------

private void enterTypeofinsurance() {
            
       int choice;
       
       System.out.println("\nPlease enter the Type of Insurance [1] Fully Comprehensive [2] Third Party Fire And Theft [3] Third Party Only");
            choice = userInput.nextInt();
            
       if ( choice == 1 ) 
           typeofinsurance = " Fully Comprehensive ";
           else 
           if (choice == 2) 
               typeofinsurance = " Third Party Fire And Theft";
               else if ( choice == 3) 
                   typeofinsurance = "Third Party Only";
                   else 
                        System.out.println ("Invalid Input");

        setTypeofinsurance(typeofinsurance);
}

//--------------------------------------------------------------------------------------------------------------

private void enterNcbyears() { 
            
        do
        {
            System.out.println("\nPlease enter the amount of NCB years");
            ncbyears = userInput.next();
                                                
            Validation = checkNcbyears(ncbyears);

            if (Validation == false)
            {
                System.out.println("ENTER A VALID amount of NCB years from [0] to [6] Years");
            }
        }
        while (Validation == false);

        setNcbyears(ncbyears);
}

public static boolean checkNcbyears(String ncbyears)
     {
       return ncbyears.matches("[0-6]" );
}

//--------------------------------------------------------------------------------------------------------------

private void enterDiscount() {
            
       int choice;
             
       System.out.println("\nPlease enter the Discount Code [1] New Client = 10% ");
            choice = userInput.nextInt();
            
       if ( choice == 1 ) 
           discount = 10;
            else 
              System.out.println ("Invalid Input");
       
      String DiscounttoString = Double.toString(discount) + " ";
      setDiscount(discount);
}

//--------------------------------------------------------------------------------------------------------------

private void enterClaim() {
            
        do
        {
            System.out.println("\nDoes Policy Holder have a Claim [Y] or [N] ?");
            claim = userInput.next();
                                                
            Validation = checkClaim(claim);

            if (Validation == false)
            {
                System.out.println("INVALID INPUT");
            }
        }
        while (Validation == false);

        setClaim(claim);
}

public static boolean checkClaim(String claim)
     {
       return claim.matches("[YNyn]" );
}

//--------------------------------------------------------------------------------------------------------------

private void enterFault() {
        
    int choice;
             
       System.out.println("\nClaim Fault Code [1] No Fault [2] Blame [3] Part Blame [4] No Claim");
            choice = userInput.nextInt();
            
       if ( choice == 1 ) 
           fault = "No Fault";
            else if( choice == 2)
                fault = "Blame";
                    else if (choice == 3)
                        fault = "Part Blame";
                            else if ( choice ==4)
                                fault = "No Claim";
                                    else
                                        System.out.println ("Invalid Input");    

        setFault(fault);
}

//--------------------------------------------------------------------------------------------------------------

private void enterPsd() {
                  
         SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy");

         psd = df.format(new Date());

         setPsd(psd);
}

//--------------------------------------------------------------------------------------------------------------

private void enterPed() {
                    

         Calendar now = Calendar.getInstance();
         Calendar working;
         SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
         
         working = (Calendar) now.clone();
         working.add(Calendar.DAY_OF_YEAR, + 364);
         ped =  formatter.format(working.getTime());

         setPed(ped);
}

//--------------------------------------------------------------------------------------------------------------

private void enterDob() throws IOException {
                       
        SimpleDateFormat DateofBirth = new SimpleDateFormat("MM/dd/yyyy");

        // not lenient, otherwise 02/29/2003 becomes 03/01/2003!
        DateofBirth.setLenient(false);

        // get a date from the user, show them the expected format
        System.out.print("\nEnter Policy Holder Date Of Birth (" + DateofBirth.toPattern().toLowerCase() + "): ");
        DOB = userInput.next();

        // see if it's a valid date; if so then show it
        try
        {
            Date d = DateofBirth.parse(DOB);
            System.out.println("Valid Date : " + DateofBirth.format(d));
        }
        catch (ParseException pe)
        {
            System.out.println("Invalid Date enter again");
        }
        
        setDOB(DOB);
}

}// end policy class

I hope someone can help me out since i have come so far. Thanks for reading and helping out. Looking forward to a reply.

Recommended Answers

All 4 Replies

Loop through all elements in the PolicyInfo array and retrieve the policy ID from that element. When it equals the ID you're looking for, that's the policy object you want.

Member Avatar for TheStig01

ok well i have done this so far without any luck :(

public void searchID() {
        String userID;
        
        Scanner scanner = new Scanner(System.in);
        
        System.out.println("Please enter the ID number you wish to search");
        userID = scanner.next();

        for (Iterator it = PolicyInfo.iterator(); it.hasNext(); )
        {
            String s = (String) it.next();
            if (s.equals(userID))
            {
                PolicyInfo.get(stringLine);
}
}  
}

If someone can help me out with the code it would really help. Thanks.

I took another look at your program. Currently, what you're doing is getting a policy number from the client then comparing it to the strings in the array. That's all fine and dandy, except you seem to have forgotten what strings are in your array. Look at your addPolicyRecord() method again. See that big messy string you're adding to the array list? You should store Policy objects into the array list.

Ignoring for the moment that I don't see an iterator method in your PolicyTable class (maybe I just over looked it).

/**
 * @param policyId	The policy id as entered by the client
 * @return 		The policy matching the given id or null if no match found
 */
public getPolicyById(String policyId){		
	String pn = "user entered policy number";

	for(int i=0;i<policyInfo.size();i++){
		Policy p = (Policy)policyInfo.get(i);
		if (pn.equals(p.getPolicyNo()))
			return p;
	}
	return null;
}

There's another option as well. If this was a small list of policies that required frequent lookups, I'd probably use a Map.

HashMap<String, Policy> policies = new HashMap<String, Policy>()
policies.put("123456789", new Policy());
String policyId = "123456789";
Policy policy = policies.get(policyId);
commented: thanks +1
Member Avatar for TheStig01

Thanks it actually worked with a few tweaks to my program . Really appreciate it Phaelex.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.