Java Modify provided code to UML USE REGULAR EXPRESSION WHERE REQUIRED PROVIDED
ID: 3705954 • Letter: J
Question
Java
Modify provided code to UML
USE REGULAR EXPRESSION WHERE REQUIRED
PROVIDED CODE:
import java.text.NumberFormat;
public class Annuity implements BookValue
{
//instance variables
private String owner;
private String beneficiary;
private String contractNbr;
private int contractValue;
private double cashBalance;
//null constructor
public Annuity()
{
}
//full constructor
public Annuity(String own,String beni,String nbr,int value,double bal)
{
setOwner(own);
setBeneficiary(beni);
setContractNbr(nbr);
setContractValue(value);
setCashBalance(bal);
}
/*
* SET METHODS
*/
public final void setOwner(String own)
{
owner = own;
}
public final void setBeneficiary(String beni)
{
beneficiary = beni;
}
public final void setContractNbr(String nbr)
{
contractNbr = nbr;
}
public final void setContractValue(int value)
{
contractValue = value;
}
public final void setCashBalance(double bal)
{
cashBalance = bal;
}
/*
* GET METHODS
*/
public final String getOwner()
{
return owner;
}
public final String getBeneficiary()
{
return beneficiary;
}
public final String getContractNbr()
{
return contractNbr;
}
public final int getContractValue()
{
return contractValue;
}
public final double getCashBalance()
{
return cashBalance;
}
/*
* OTHER METHODS AS NEEDED
*/
//returns the contract number
public String identifyContract()
{
return contractNbr;
}
//calculates exposure value with provided formula
public double calcExposure()
{
return getContractValue() - getCashBalance();
}
//returns the cashBalance
public double calcCurrentValue()
{
return getCashBalance();
}
//Outputs a formatted string with data for an annuity object
public String toString()
{
NumberFormat nf = NumberFormat.getInstance();//Creates Number Format Object
String Contract = nf.format(getContractValue());//formats contract value
String CashBal = nf.format(getCashBalance());//formats cashBalance
return String.format("%s owns an Annuity contract, %s, benefitting %s. Total contract value is $%s.00. Current cash value is $%s "
,getOwner(),getContractNbr(),getBeneficiary(),Contract,CashBal);
}
}//end class
/////////////////////////////////////////////////////////////////////////////////////////////////
import java.text.NumberFormat;
public class Auto extends Policy
{
//instance variables
private double exposureRate;
private String makeModel;
private int modelYear;
private String vin;
private int limits[] = new int[3];
private int deduct;
//null constructor
public Auto()
{
super();
}
//Full constructor
public Auto(String own,String insd,String nbr,double prem,String model,int year,String id,int[]lims,int ded)
{
super(own,
insd,
nbr,
prem);
setExposureRate();
setMakeModel(model);
setModelYear(year);
setVin(id);
setLimits(lims);
setDeduct(ded);
}
/*
* SET METHODS
*/
public final void setExposureRate()
{
exposureRate = .0051;//sets exposureRate explicitly
}
public final void setMakeModel(String model)
{
makeModel = model;
}
public final void setModelYear(int year)
{
modelYear = year;
}
public final void setVin(String id)
{
vin = id;
}
public final void setLimits(int[] lims)
{
limits = lims;
}
public final void setDeduct(int ded)
{
deduct = ded;
}
/*
* GET METHODS
*/
public final double getExposureRate()
{
return exposureRate;
}
public final String getMakeModel()
{
return makeModel;
}
public final int getModelYear()
{
return modelYear;
}
public final String getVin()
{
return vin;
}
public final int[] getLimits()
{
return limits;
}
public final int getDeduct()
{
return deduct;
}
/*
* OTHER METHODS AS NEEDED
*/
//converts ints from the limits array to a formatted string and returns it.
public String produceLimitsTxt()
{
String[]LimitHold = new String[3];//creates an array to store formatted numbers
NumberFormat nf = NumberFormat.getInstance();//creates numberformat object
for(int ctr = 0; ctr < getLimits().length;ctr++)
{
LimitHold[ctr] = nf.format(getLimits()[ctr] * 1000);//uses numberformat to format to correct US standard and store them in the array
}
return String.format("Collision: $%s.00, Comprehensive: $%s.00, UIM:$%s.00",LimitHold[0],LimitHold[1],LimitHold[2]);
}
//calculates exposure using values passed in the array
public double calcExposure()
{
double tmp = getLimits()[0]+getLimits()[1]+getLimits()[2];
return tmp * 1000;
}
//calculates current value using provided equation
public double calcCurrentValue()
{
return getPolPrem() - (calcExposure() * getExposureRate());//simplified to one line for simplicity
}
//auto toString function, concatenates superclass toString with subclass variables to produce a formatted sentence.
public String toString()
{
NumberFormat Form = NumberFormat.getInstance();//creates number format object to format deductible var
//super.toString provides us the base value sentence already formatted, here we just add the auto specific data to it
return String.format(super.toString()+" This Auto policy " +
"insures a %d %s, VIN %s with limits of %s and a deductible of $%s.00 ",
getModelYear(),getMakeModel(),
getVin(),produceLimitsTxt(),Form.format(getDeduct()));
}
}//end class
/////////////////////////////////////////////////////////////////////////////////////////////////
public interface BookValue
{
public String identifyContract();
public double calcExposure();
public double calcCurrentValue();
}//end interface
/////////////////////////////////////////////////////////////////////////////////////////////////
import java.text.NumberFormat;
public class HomeOwners extends Policy implements BookValue
{
//instance variables
private double exposureRate;
private String propAddress;
private int propType;
private int structure;
private int contents;
private double deduct;
private boolean umbrella;
//Homeowners null constructor
public HomeOwners()
{
super();
}
//Homeowners Full constructor
public HomeOwners(String own,String insd,String nbr,double prem,String addr, int type,int struct,int goods,double ded,boolean umbr)
{
super(own,
insd,
nbr,
prem);
setExposureRate();
setPropAddress(addr);
setPropType(type);
setStructure(struct);
setContents(goods);
setDeduct(ded);
setUmbrella(umbr);
}
/*
* SET METHODS
*/
public final void setExposureRate()
{
exposureRate = .0025;//explicitly sets exposure rate
}
public final void setPropAddress(String addr)
{
propAddress = addr;
}
public final void setPropType(int type)
{
propType = type;
}
public final void setStructure(int struct)
{
structure = struct;
}
public final void setContents(int goods)
{
contents = goods;
}
public final void setDeduct(double ded)
{
deduct = ded;
}
public final void setUmbrella(boolean umbr)
{
umbrella = umbr;
}
/*
* GET METHODS
*/
public final double getExposureRate()
{
return exposureRate;
}
public final String getPropAddress()
{
return propAddress;
}
public final int getPropType()
{
return propType;
}
public final int getStructure()
{
return structure;
}
public final int getContents()
{
return contents;
}
public final double getDeduct()
{
return deduct;
}
public final boolean getUmbrella()
{
return umbrella;
}
/*
* OTHER METHODS AS NEEDED
*/
//calculates the deductible with provided formula
public double getDeductInDollars()
{
return (getStructure() + getContents()) * getDeduct();
}
//calculates Exposure based on provided equation, we multiply by 1000 to return the real value
public double calcExposure()
{
return (getStructure() + getContents()) * 1000;
}
//calculates current value based on equation provided
public double calcCurrentValue()
{
return getPolPrem() - (calcExposure() * getExposureRate());
}
//shows output
public String toString()
{
String boo;//defines a string boo which will be inserted into the String
if(getUmbrella())//Determines whether getUmbrella is true or false
boo = "is";//If it is true, sets boo to "is" which is the correct language for the string below.
else
boo = "is not";//If it is not true sets boo to "is not" which is the correct language for the string below.
//begin number formatting
//Number format object creation
NumberFormat nf = NumberFormat.getInstance();
//Assigns values to strings with proper US formatting.
String StructHold = nf.format(getStructure() * 1000);
String ContHold = nf.format(getContents() * 1000);
String DedHold = nf.format(getDeductInDollars() * 1000);
//end number formatting
//below assignment uses super.toString to get the base formatted string from Policy and appends the relevant data specific to homeowners.
return String.format(super.toString()+" This HomeOwners policy insures a type %d home at %s. The structure is insured for $%s.00; " +
"contents for $%s.00. The deductible is $%s.00. This policy %s part of an Umbrella contract. "
,getPropType(),getPropAddress(),StructHold,ContHold,DedHold,boo);
}
}//end class
/////////////////////////////////////////////////////////////////////////////////////////////////
import java.text.NumberFormat;
public abstract class Policy implements BookValue
{
//Instance Variables
private String owner, insured, polNbr;
private double polPrem;
//Null constructor
public Policy()
{
}
//Full constructor
public Policy(String own, String insd, String nbr, double prem)
{
setOwner(own);
setInsured(insd);
setPolNbr(nbr);
setPolPrem(prem);
}
/*
* SET METHODS
*/
public final void setOwner(String own)
{
owner = own;
}
public final void setInsured(String insd)
{
insured = insd;
}
public final void setPolNbr(String nbr)
{
polNbr = nbr;
}
public final void setPolPrem(double prem)
{
polPrem = prem;
}
/*
* GET METHODS
*/
public final String getOwner()
{
return owner;
}
public final String getInsured()
{
return insured;
}
public final String getPolNbr()
{
return polNbr;
}
public final double getPolPrem()
{
return polPrem;
}
/*
* OTHER METHODS AS NEEDED
*/
//returns the policy number
public String identifyContract()
{
return polNbr;
}
//converts data to a formatted sentence
public String toString()//Superclass toString method, formats base data for both types of insurance
{
NumberFormat nf = NumberFormat.getInstance();//initialize NumberFormat object
String Prem = nf.format(getPolPrem());//uses NumberFormat to convert PolPrem to a String with the correct formatting
return String.format("%s owns Policy %s, insuring %s, with a premium of $%s",
getOwner(),getPolNbr(),getInsured(),Prem);
}
}//end class
///////////////////////////////////////////////////////////////////
Test Harness
Helper class
Policy (abstract) implements BookValue Attributes Notes private owner: String Policy owner's full, legal name is may not be a null String or all spaces; if the offered value is null or all spaces, throw an exception and do not create the Policy object. private insured: String Full, legal name of named insured on policy is may not be a null String or all spaces; if the offered value is null or all spaces, throw an exception and do not create the Policy object. private polNbr: String Unique identifier for specific policy This policy number must meet these requirements: The first two (2) characters must be alphabetic These will be followed by exactly 5 digits If the offered value does not meet the requirements, throw an exception and do not create the Policy object Use a regular expression to validate the offered value Annual private polPrem: double amount for Operations public Policy( ): Policy public Policyl String own, Description Null constructor; establishes no instance variable values Constructor accepts four (4) parameter values, calls set methods and establishes instance variable values as appropriate String insd, String nbr ??): Poli ublic identifyContract Stri Returns o?Nbr public tostring : String Returns a String reference to a formatted description of the Policy object: owner owns Policy polNbr insuring insured, with a premium of polPrem NOTES Set & get methods are not listed here, but are assumed to be nt. Further, standard naming is assumeExplanation / Answer
// Auto.java toString enhancements
public String toString()
{
StringBuilder myStringBuilder = new StringBuilder();
NumberFormat Form = NumberFormat.getInstance();//creates number format object to format deductible var
//super.toString provides us the base value sentence already formatted, here we just add the auto specific data to it
myStringBuilder.append(super.toString()).append(" This Auto policy insures a ").append(getModelYear()).append(" ").append(getModelYear());
myStringBuilder.append(" , VIN ").append(getVin()).append(" with limits of ").append(produceLimitsTxt());
myStringBuilder.append(" and a deductible of ").append(Form.format(getDeduct()));
// return String.format(super.toString()+" This Auto policy " +
// "insures a %d %s, VIN %s with limits of %s and a deductible of $%s.00 ",
// getModelYear(),getMakeModel(),
// getVin(),produceLimitsTxt(),Form.format(getDeduct()));
return myStringBuilder.toString();
}
//////// UPDATED Test_XcptnHandling CLASS WITH REGEX VALIDATION OVER POLIC NUM AND VIN //////////////
////////ADDED METHOD private static void policyNumberValidation(String pol) throws PolicyException . and
//////// private static void vinValidation(String vin) throws PolicyException
package solution.policy;
public class Test_XcptnHandling {
// This object ( myPolicy) provides a 'holding space' for a reference to an
// object in the InsurancePolicy hierarchy.
// NOTE: We are NOT INSTANTIATING an InsurancePolicy object here, just
// setting up a reference.
private static Policy myPolicy;
/*************************************************************************************************************
* The main method will consist of a continuous input loop based on the
* boolean variable goAgain. Use a while loop (while goAgain = true) to
* contol processing: Ask user which type of policy to create If Auto call
* method to create Auto object ElseIf HomeOwners call method to create
* HomeOwners object Else Tell user valid options Ask user whether to
* continue
*************************************************************************************************************/
public static void main(String[] args) {
boolean goAgain = true; // Set the initial value of the loop control
// variable to continue the loop.
while (goAgain) // Initiate an input loop based on the control variable
{
try // The try block is placed INSIDE the loop to allow continous
// input
{
/*
* The following statement calls the acceptString method of
* KeyboardInput. The charAt method of the returned String
* object is then called to retrieve the first character of the
* String. That char is then converted to upper case and the
* resulting value is stored in the variable polType
*/
char polType = Character
.toUpperCase(KeyboardInput
.acceptString(
"Build an Auto policy (A) or a HomeOwners policy (H)? ")
.charAt(0));
/*
* Test variable polType. If the value is 'A', go on to collect
* data to create an Auto object. If the value is 'H', collect
* data to create a HomeOwners object. If the value is neither,
* let the user know what the acceptable values are.
*/
if (polType == 'A') {
buildAutoPolicy(); // Call method to collect data and
// instantiate an Auto object
} else if (polType == 'H') {
buildHomeOwnersPolicy(); // Call method to collect
// data/instantiate a HomeOwners
// object
} else {
// Remind user of the acceptable responses to the question
// about policy type...
System.out.printf("%n%s%n",
"You must select Auto (A) or HomeOwners (H).");
}
} // end try block
catch (PolicyException buildError) {
// Catch any validation exception that may have been thrown and
// display to the console.
System.out.printf("%n%s%n", buildError.getMessage());
} // end catch block
// Aks user if they wish to continue the loop -- the loop does not
// end if a PolicyException was thrown.
goAgain = KeyboardInput
.acceptBoolean("Do you wish to enter another? true or false ");
} // end while loop
System.out.printf("%nThanks for playing!%n");
} // end main method
/*************************************************************************************************************
* Use methods of KeyboardInput to deliver prompts and accept input from
* user. Collect values for all non-static instance variables fo class Auto.
* Instantiate an Auto object using those values; assign the object
* reference to myPolicy Call the toString method of myPolicy to output
* information about the instantiated object
*
* IF a PolicyException is thrown, it is NOT CAUGHT AT THIS LEVEL; it is
* 'passed through' to the main method and will be caught & handled there.
*************************************************************************************************************/
private static void buildAutoPolicy() throws PolicyException {
// Variables to hold values required for the superclass level
// (InsurancePolicy)
String own, insd, pol;
double prem;
// Variables to hold values required for Auto subclass
String mkMod, vin;
int year, coll, comp, uim, ded;
int[] limits = new int[3];
// Gather superclass level values
own = KeyboardInput.acceptString("Policy Owner: ");
insd = KeyboardInput.acceptString("Insured: ");
pol = KeyboardInput
.acceptString("Policy Number (2 letters, 5 digits): ");
policyNumberValidation(pol);
prem = KeyboardInput.acceptDouble("Annual premium (no dollar sign): ");
// Gather Auto subclass level values
mkMod = KeyboardInput
.acceptString("Make & Model (i.e., Ford Fusion): ");
year = KeyboardInput.acceptInteger("Year of car (four digits): ");
vin = KeyboardInput.acceptString("VIN (17 characters): ");
vinValidation(vin);
coll = KeyboardInput
.acceptInteger("Collision limit (no dollar sign): ");
comp = KeyboardInput
.acceptInteger("Compehensive limit (no dollar sign): ");
uim = KeyboardInput
.acceptInteger("Uinsured Motorist limit (no dollar sign): ");
ded = KeyboardInput.acceptInteger("Deductible (no dollar sign): ");
// load limits array
limits[0] = coll;
limits[1] = comp;
limits[2] = uim;
// Instantiate object; set myPolicy to refer to new object
myPolicy = new Auto(own, insd, pol, prem, mkMod, year, vin, limits, ded);
System.out.printf("%n%s%n", myPolicy.toString());
} // end buildAutoPolicy
/**
* @category Validating eneterd vin that it should be of length 17
* containing no special characters and all capital letters Except
* I, O, Q
* @param vin
* @throws PolicyException
*/
private static void vinValidation(String vin) throws PolicyException {
boolean result = false;
if (vin != null && vin.trim().length() == 17) {
String vinRegex = "[A-Z0-9&&[^IOQ]]+";
if (vin.matches(vinRegex))
result = true;
}
if (!result) {
throw new PolicyException("Entered Policy Number is not Valid.");
}
}
private static void policyNumberValidation(String pol)
throws PolicyException {
boolean result = false;
if (pol != null && pol.trim().length() == 7) {
String firstTwoCharacters = pol.substring(0, 2);
String nextFiveCharacters = pol.substring(2, 7);
String regex1 = "[a-zA-Z]+";
String regex2 = "\d+";
if (firstTwoCharacters.matches(regex1)
&& nextFiveCharacters.matches(regex2))
result = true;
}
if (!result) {
throw new PolicyException("Entered Policy Number is not Valid.");
}
}
/*************************************************************************************************************
* Use methods of KeyboardInput to deliver prompts and accept input from
* user. Collect values for all non-static instance variables fo class
* HomeOwners. Instantiate an HomeOwners object using those values; assign
* the object reference to myPolicy Call the toString method of myPolicy to
* output information about the instantiated object
*
* IF a PolicyException is thrown, it is NOT CAUGHT AT THIS LEVEL; it is
* 'passed through' to the main method and will be caught & handled there.
*************************************************************************************************************/
private static void buildHomeOwnersPolicy() throws PolicyException {
// Variables to hold values required for the superclass level
// (InsurancePolicy)
String own, insd, pol;
double prem;
// Variables to hold values required for HomeOwners subclass
String address;
int type, struct, cont;
double deduct;
boolean umb;
// Gather superclass level values
own = KeyboardInput.acceptString("Policy Owner: ");
insd = KeyboardInput.acceptString("Insured: ");
pol = KeyboardInput
.acceptString("Policy Number (2 letters, 5 digits): ");
prem = KeyboardInput.acceptDouble("Annual premium (no dollar sign): ");
// Gather HomeOwners subclass level values
address = KeyboardInput.acceptString("Property Address: ");
type = KeyboardInput.acceptInteger("Property Type Code (1 - 5): ");
struct = KeyboardInput.acceptInteger("Insured value of structure: ");
cont = KeyboardInput.acceptInteger("Insured value of contents: ");
deduct = KeyboardInput
.acceptDouble("Deductible as a Percentage of value (i.e., .05 for 5%): ");
umb = KeyboardInput
.acceptBoolean("Is this part of an Umbrella contract (true or false)?");
// Instantiate object; set myPolicy to refer to new object
myPolicy = new HomeOwners(own, insd, pol, prem, address, type, struct,
cont, deduct, umb);
System.out.printf("%n%s%n", myPolicy.toString());
} // end buildHomeOwnersPolicy
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.