Class "Savings"..
int id, String name, double balance, double interestRate
Add a constructor of Savings that receives four parameters: id, name, balance, interest rate. Validate that interest rate is greater than zero, and add set & get methods.
I know how to do most of the above, but how do I validate that the interest rate is greater than 0? Can you give a few random examples of validating variables? Does this happen in the set/get methods?
Most practical way is to use setters for validation.
public Savings(int id, String name, double balance, double interestRate) {
setId(id);
setName(name);
setBalance(balance);
setInterestRate(interestRate);
}
...
public void setInterestRate(double interestRate) {
if(interestRate > 0) {
this.interestRate = interestRate;
} else {
throw new IllegalArgumentException("Given value must be greater than zero");
}
}
You also can simply validate value in the constructor by adding "if" statement and throwing an exception if data is invalid:
public Savings(int id, String name, double balance, double interestRate) {
this.id = id;
this.name = name;
this.balance = balance;
if(interestRate > 0) {
this.interestRate = validate(interestRate);
} else {
throw new IllegalArgumentException("Given value must be greater than zero");
}
}
Or you can create validate function and call it within constructor:
private double validate(double param) {
if(param > 0) {
return param;
}
throw new IllegalArgumentException("Given value must be greater than zero");
}
public Savings(int id, String name, double balance, double interestRate) {
this.id = id;
this.name = name;
this.balance = balance;
this.interestRate = validate(interestRate);
}
You also need to validate value in the set method. See example in the attachment. You may also change the return type of validate function to "void":
private void validate(double param) {
//Some code here
}
public Savings(int id, String name, double balance, double interestRate) {
//Some code here
validate(interestRate);
this.interestRate = interestRate;
}
Need a fast expert's response?
Submit order
and get a quick answer at the best price
for any assignment or question with DETAILED EXPLANATIONS!
Learn more about our help with Assignments:
JavaJSPJSF