Java中对象数组中的对象数组

时间:2018-05-08 13:23:57

标签: java arrays object

我正在做一个学校作业,我真的在努力解决这个问题的一部分。我们的代码基本上要求我们在每个产品组合中拥有多个包含多个策略的Portfolio组合。我需要创建一个对象数组才能执行此操作吗?请记住,投资组合和政策都是对象。任何帮助将不胜感激,因为我非常困惑这一个。提前谢谢!

import java.text.DateFormat;//import Statements
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

public class Menu
{
    public static void main(String[]args)//main class
    {
        String StringDate = null;
        //Code Implemented to convert user String input to Calendar Format
        DateFormat dateFormat = new SimpleDateFormat("DD/MM/YYYY");
        Calendar newDOB = Calendar.getInstance();
        Calendar newsDate = Calendar.getInstance();
        Calendar neweDate = Calendar.getInstance();


        //int to allow user input to navigate menu system

        int IntInput = 0;//menu class specific variables declared
        String newName;
        String newID;
        String newPolicyNum;
        String newPolicyType;
        String newStatus;
        String newPolicyName;

        //arrays declared
        Portfolio[] Portfolio = new Portfolio[1];
        MotorPolicy[] MotorPolicy = new MotorPolicy[1];
        HomePolicy[] HomePolicy = new HomePolicy[1];
        MobilePhonePolicy[] MobilePolicy = new MobilePhonePolicy[1];
        Policy[] Policy = new Policy[1];

        Scanner num = new Scanner(System.in);//scanners created
        Scanner let = new Scanner(System.in);
        Scanner keyboard = new Scanner(System.in);

        int menuChoice;

        do //do loop to run main menu
        {
            System.out.println("   --------------------Welcome to Insurance World------------------- ");
            System.out.println("   ----------Insurance That's Truely 'Out Of This World'------------ ");
            System.out.println("  |_________________________________________________________________|");
            System.out.println("1)| Create An Insurance Portfolio                                   |");
            System.out.println("  |-----------------------------------------------------------------|");
            System.out.println("2)| Amend Portfolio Details                                         |");
            System.out.println("  |-----------------------------------------------------------------|");
            System.out.println("3)| Display a Portfolio                                             |");
            System.out.println("  |-----------------------------------------------------------------|");
            System.out.println("4)| Create An Insurance Policy                                      |");
            System.out.println("  |-----------------------------------------------------------------|");
            System.out.println("5)| Amend Policy Details                                            |");
            System.out.println("  |-----------------------------------------------------------------|");
            System.out.println("6)| Cancel A Policy                                                 |");
            System.out.println("  |-----------------------------------------------------------------|");
            System.out.println("7)| Display a Policy                                                |");
            System.out.println("  |-----------------------------------------------------------------|");
            System.out.println("8)| Exit Program                                                    |");
            System.out.println("  |_________________________________________________________________|");

            menuChoice = keyboard.nextInt();//menu input

            if (menuChoice == 1)//create a portfolio
            {
                for(int i = 1; i<Portfolio.length; i++)//counter is declared 
                {
                    Portfolio[i] = new Portfolio();//Portfolio initialised  
                    System.out.println("Please Enter The Name of The Portfolio Holder: ");
                    newName=let.nextLine();

                    System.out.println("Please Enter Your DoB(DD/MM/YYYY): ");
                    StringDate=let.nextLine();

                    System.out.println("Your ID Number is: " + i);
                    newID = " " + i;

                    Portfolio[i].setId(" " + i);
                    Portfolio[i].setName(newName);//assigning values to portfolio methods
                    Portfolio[i].setDOB(newDOB);
                    Portfolio[i].setNumPolicies(0);
                    Portfolio[i].getDateCreated();

                    System.out.println("Your Portfolio Will Look Like This: ");

                    i++;//Counter incremented
                }
            }
            else if(menuChoice == 2)
            {
                //amend portfolio details

                System.out.println("Please Enter The ID Number Of The Portfolio You Wish To Amend: ");
                IntInput=num.nextInt();
                Portfolio[IntInput].toString();

                int amendChoice;
                System.out.println("What do you want to Change? ");
                System.out.println("1) Name of Portfolio Holder ");
                System.out.println("2) Date Of Birth of Portfolio Holder ");
                System.out.println("3) ID of Portfolio ");
                System.out.println("4) Exit Program ");
                amendChoice=num.nextInt();//user input

                if(amendChoice == 1)
                {
                    System.out.println("Please Enter the Updated Name of the Portfolio Holder: ");
                    newName=let.nextLine();
                    Portfolio[IntInput].setName(newName);
                    System.out.println("Your New Portfolio Will Look Like This: ");
                    Portfolio[IntInput].toString();
                }
                else if(amendChoice == 2)
                {
                    System.out.println("Please Enter the Updated DOB of the Portfolio Holder: ");
                    //newDOB=keyboard.nextLine();
                    Portfolio[IntInput].setDOB(newDOB);
                    System.out.println("Your New Portfolio will Look Like This: ");
                    Portfolio[IntInput].toString();
                }
                else if(amendChoice == 3)
                {
                    System.out.println("Please Enter the Updated ID of the Portfolio: ");
                    newID=let.nextLine();
                    Portfolio[IntInput].setId(newID);
                    System.out.println("Your New Portfolio Will Look Like This: ");
                    Portfolio[IntInput].toString();
                }
                else if(amendChoice == 4)
                {
                    System.out.println("Exiting Menu");
                }
                else
                {
                    System.out.println("The Number You Entered isn't a Valid Choice");
                }
            }
            else if(menuChoice == 3)//display portfolio details
            {

                System.out.println("Please Enter the ID of the Portfolio you wish to View: ");
                Portfolio[num.nextInt()].toString();
            }
            else if(menuChoice == 4)//create a new policy
            {
                int Counter=1;
                do
                {
                    int subMenuChoice;//Menu to Choose policy type
                    System.out.println("Please Choose The type of Policy You Want: ");
                    System.out.println("1) Motor Insurance Policy");
                    System.out.println("2) Home Insurance Policy");
                    System.out.println("3) Mobile Phone Insurance Policy");
                    System.out.println("4) Travel Insurance Policy");
                    subMenuChoice=num.nextInt();

                    if(subMenuChoice==1)
                    {
                        MotorPolicy[Counter] = new MotorPolicy();

                        MotorPolicy[Counter].setPolicyType("Motor Insurance");
                        MotorPolicy[Counter].setPolicyNum(" " + Counter);

                        System.out.println("Please Enter the Name of the Policy Holder: ");
                        newPolicyName=let.nextLine();
                        MotorPolicy[Counter].setPolicyName(newPolicyName);

                        System.out.println("Please Enter Your DoB (DD/MM/YYYY): ");
                        StringDate=let.nextLine();
                        MotorPolicy[Counter].setDob(newDOB);

                        System.out.println("Please Enter The Date You Want Your Policy To Start (DD/MM/YYYY): ");
                        StringDate=let.nextLine();
                        MotorPolicy[Counter].setSDate(newsDate);

                        System.out.println("Please Enter The Date You Want Yourt Policy To End (DD/MM/YYYY): ");
                        StringDate=let.nextLine();
                        MotorPolicy[Counter].setEDate(neweDate);

                        System.out.println("Please Enter the Registration Number of your Car: ");
                        int newRegNum = num.nextInt();
                        MotorPolicy[Counter].setCarRegistrationNumber(newRegNum);

                        System.out.println("Please Enter The Model of Your Car: ");
                        String newModel = let.nextLine();
                        MotorPolicy[Counter].setModel(newModel);

                        System.out.println("Please Enter The Value Of Your Car: ");
                        double newValue = num.nextDouble();
                        MotorPolicy[Counter].setVehicleValue(newValue);

                        System.out.println("We Will Calculate Your Motor Insurance Premium!");
                        MotorPolicy[Counter].calcMotorPremium(newsDate, neweDate, newValue);
                        System.out.println("We Calculated Your Premium to Be: £" + MotorPolicy[Counter].getPremium());
                        Counter++;
                    }
                    else if(subMenuChoice==2)
                    {
                        Policy[Counter].setPolicyType("Home Insurance");

                        Counter++;
                    }
                    else if(subMenuChoice==3)
                    {
                        Policy[Counter].setPolicyType("Mobile Phone Insurance");

                        Counter++;
                    }
                    else if(subMenuChoice==4)
                    {
                        Policy[Counter].setPolicyType("Travel Insurance");

                        Counter++;
                    }
                    else
                    {
                        System.out.println("The Number You Entered Doesn't Correspond To A Choice!");//Validation for policy choice menu
                    }
                }
                while(Counter<10);
            }
            else if(menuChoice == 5)
            {
                //amend policy details
            }
            else if(menuChoice == 6)
            {
                //cancel policy
            }
            else if(menuChoice == 7)
            {
                //display policy
                System.out.println("Please Enter The Policy Number of The Policy You Want to View: ");
                IntInput = let.nextInt();
                Policy[IntInput].toString();
                //IntInput = keyboard.nextInt();
                //Portfolio[IntInput].toString();
            }
            else
            {
                System.out.println("The Input you entered doesn't correspond to a choice!");//validation method 
            }
        }

        while(menuChoice != 8); //exit condition
        {
            System.out.println("Exiting Program!");
        }
    }
}

投资组合类:

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;//import statements


public class Portfolio 
{
    private String id;//variables declared
    private String name;
    private Calendar dob;
    private Calendar dateCreated;
    private int numPolicies;




    public Portfolio(String id, String name, Calendar dob)//portfolio constructor
    {
        this.id=id;
        this.name=name;
        this.dob=dob;
        dateCreated = Calendar.getInstance();
        numPolicies=0;
    }

    public Portfolio()
    {
        id = " ";//variables given null values
        name = " ";
        dob = null;
        dateCreated = null;
        numPolicies = 0;
    }


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

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

    public void setDOB(Calendar dob)
    {
        this.dob=dob;
    }

    public void setDateCreated(Calendar dateCreated)
    {
        this.dateCreated=dateCreated;
    }

    public void setNumPolicies(int numPolicies)
    {
        this.numPolicies=numPolicies;
    }

    public String getId()//get methods
    {
        return id;
    }

    public String getName()
    {
        return name;
    }

    public Calendar getDob()
    {
        return dob;
    }

    public Calendar getDateCreated()
    {
        return dateCreated;
    }

    public void acceptPolicy(Policy p)//accept a policy 'p' and link it to the portfolio
    {
        p.setPortfolio(this);
        p.setStatus("ACTIVE");
        numPolicies = numPolicies +1;//adds one policy to the portfolio
    }

    public String toString()//method to output portfolio data
    {
        String str = " ";
        str = str + "ID: " + id + "\n";
        str = str + "Name: " + name + "\n";

        if(dob!=null)
        {
            str = str + "DOB: " + dob.get(Calendar.DATE) + "/" + (dob.get(Calendar.MONTH) + 1) + dob.get(Calendar.YEAR) + "\n";
        }
        if(dateCreated!=null)
        {
            str = str + "Date Created: " + dateCreated.get(Calendar.DATE) + "/" + (dateCreated.get(Calendar.MONTH) + 1) + dateCreated.get(Calendar.YEAR) + "\n"; 
        }

        str = str + "Number of Policies: " + numPolicies + "\n";
        return str;
    }



}

政策类:

import java.util.Calendar;
class Policy
{

    private String policyNum, Pname, policyType, status;
    private Calendar dob, sDate, eDate;
    private double dailyRate, premium;
    private Portfolio portfolio;

    public Policy(String policyNum, String Pname, Calendar dob, Calendar sDate, Calendar eDate, String policyType, double dailyRate )
    {
        this.policyNum = policyNum;
        this.Pname = Pname;
        this.dob = dob;
        this.sDate = sDate;
        this.eDate = eDate;
        this.policyType = policyType;
        status = " ";
        this.dailyRate = dailyRate;
        premium = 0;
        portfolio = null;
    }

    public Policy()
    {
        policyNum = " ";
        Pname = " ";
        dob = null;
        sDate = null;
        eDate = null;
        policyType = " ";
        status = " ";
        dailyRate = 0;
        premium = 0;
        portfolio = null;
    }

    //set methods
    public void setPolicyNum (String policyNum)
    {
        this.policyNum = policyNum;
    }

    public void setPolicyName (String Pname)
    {
        this.Pname = Pname;
    }

    public void setDob (Calendar dob)
    {
        this.dob = dob;
    }

    public void setSDate (Calendar sDate)
    {
        this.sDate = sDate;
    }

    public void setEDate (Calendar eDate)
    {
        this.eDate = eDate;
    }

    public void setPolicyType (String policyType)
    {
        this.policyType = policyType;
    }

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

    public void setDailyRate (double dailyRate)
    {
        this.dailyRate = dailyRate;
    }

    public void setPremium (double premium)
    {
        this.premium = premium;
    }

     public void setPortfolio (Portfolio portfolio)
     {
        this.portfolio = portfolio;
    }

    //get methods
    public String getPolicyNum()
    {
        return policyNum;
    }

    public String getPolicyName()
    {
        return Pname;
    }

    public Calendar getDob()
    {
        return dob;
    }

    public Calendar getSDate()
    {
        return sDate;
    }

    public Calendar getEDate()
    {
        return eDate;
    }

    public String getPolicyType()
    {
        return policyType;
    }

    public String getStatus()
    {
        return status;
    }

    public double getDailyRate()
    {
        return dailyRate;
    }

    public double getPremium()
    {
        return premium;
    }

    public Portfolio getPortfolio()
    {
        return portfolio;
    }

    public void cancelPolicy(Calendar eDate)
    {
        this.eDate = eDate;
        status = "CANCELLED";
    }

    public double calcPremium()
    {
        //work out number of days of policy and calculate premium based on a daily rate
        if(sDate!= null && eDate!= null)
        {
            long time1 = sDate.getTimeInMillis();
            long time2 = eDate.getTimeInMillis();
            long diff = time2 - time1;
            long days = diff/1000/60/60/24;

            return (days * dailyRate);
        }
        else
            return 0;
    }

    public String toString()
    {
        String str = " ";
        str = str + "Policy Number: " + policyNum + "\n";
        str = str + "Name: " + Pname + "\n";

        if (dob!= null)
        {
            str = str + "DOB: "+ dob.get(Calendar.DATE) +  "/" + (dob.get(Calendar.MONTH) + 1) + dob.get(Calendar.YEAR) + "\n";
        }
        if (sDate!= null)
        {
            str = str + "Start Date: "+ sDate.get(Calendar.DATE) +  "/" + (sDate.get(Calendar.MONTH) + 1) + sDate.get(Calendar.YEAR) + "\n";
        }
        if (eDate!= null)
        {
            str = str + "Start Date: "+ eDate.get(Calendar.DATE) +  "/" + (eDate.get(Calendar.MONTH) + 1) + eDate.get(Calendar.YEAR) + "\n";
        }
        str = str + "Policy Type: " + policyType + "\n";
        str = str + "Policy Status: " + status + "\n";
        str = str + "Policy Daily Rate: " + dailyRate + "\n";
        if (portfolio!= null)
        {
            str = str + "Related Portfolio Reference: " + portfolio.getId() + "\n";
        }
        str = str + "Policy Premium: " + premium + "\n";
        return str;
    }

1 个答案:

答案 0 :(得分:0)

正如@jsheeran所说,你应该将一些责任委托给方法。这有助于您编写更多可重用的代码,并更容易找到错误。然后,如果您以后想要更新代码/更改功能,您只需(通常)只需修改方法而不是搜索代码以找到您需要更改的内容。此外,最好只从控制台中读取一个Scanner对象。现在回答你的问题

我要解决这个问题的方法是让Portfolio类有一个存储Policy个对象的arrayList属性(因为这是投资组合的全部目的)ArrayList可以改变大小它最好用。

类似于:

private ArrayList<Policy> policies;
//getters and setters

然后在您的主要内容中,您只需创建一个ArrayList投资组合对象,并将策略添加到每个Portfolio对象。

ArrayList<Portfolio> portfolios = new ArrayList<>();
//Add your porfolios

然后你可以像在原始程序中那样做所有事情