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?
1
Expert's answer
2016-04-29T09:37:03-0400
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"); }
Numbers and figures are an essential part of our world, necessary for almost everything we do every day. As important…
APPROVED BY CLIENTS
Finding a professional expert in "partial differential equations" in the advanced level is difficult.
You can find this expert in "Assignmentexpert.com" with confidence.
Exceptional experts! I appreciate your help. God bless you!
Comments
Leave a comment