RetailItem Exceptions Programming Challenge 4 of Chapter 6 required you to write
ID: 3820633 • Letter: R
Question
RetailItem Exceptions Programming Challenge 4 of Chapter 6 required you to write a RetailItem class that holds data pertaining to a retail item. Write an exception class that can be instantiated and thrown when a negative number is given for the price. Write another exception class that can be instantiated and thrown when a negative number is given for the units on hand. Modify the RetailItem class so that it throws the appropriate exception when either of these errors occurs.Demonstrate the modified Retail Item class and the exception classes in a program.
Explanation / Answer
HI, Please find my implementation.
########## Exception Calsses ###############
class InvalidPriceException extends Exception{
private String message;
public InvalidPriceException(String m) {
message = m;
}
@Override
public String getMessage() {
return message;
}
}
class InvalidUnitException extends Exception{
private String message;
public InvalidUnitException(String m) {
message = m;
}
@Override
public String getMessage() {
return message;
}
}
############# RetailItem.java ##############
public class RetailItem {
private double price;
private int units;
public RetailItem() {
price = 0;
units = 0;
}
public RetailItem(int units, int price) throws InvalidPriceException, InvalidUnitException{
if(price < 0)
throw new InvalidPriceException("price can not be negative");
this.price = price;
if(units < 0){
throw new InvalidUnitException("units can not be negative");
}
this.units =units;
}
public double getPrice() {
return price;
}
public int getUnits() {
return units;
}
public void setPrice(double price) throws InvalidPriceException {
if(price < 0)
throw new InvalidPriceException("price can not be negative");
this.price = price;
}
public void setUnits(int units) throws InvalidUnitException {
if(units < 0){
throw new InvalidUnitException("units can not be negative");
}
this.units = units;
}
}
You have not give the details of RetailItem Exceptions Programming Challenge 4 of Chapter 6.
We do not have book.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.