Here’s a constructor I have for Electronics that checks if the State input is valid.
public Electronics(String name, double price, int quantity, double weight, boolean frag, String s)
{
super("Electronics",name,price,quantity,weight);
fragile=frag;
s=s.toUpperCase();
if(checkState(s)==true)
{
state=s;
}
else
{
out.println("ERROR - not a valid state abbreviation");
}
}
However in my main(), I have something like this:
public List<Item> shoppingCart = new ArrayList<Item>();
temp= new Electronics(name,price,quantity,weight, fragile, state);
...
shoppingCart.add(temp);
So even if the state abbreviation is not valid, (it just prints out that state is not valid) but the object is still added to the ArrayList. What can I do to stop the add if the state abbreviation is not correct?
You should throw an Exception and handle it in your
main(), IllegakArgumentException is probably the best fit here.Something like:
in main:
Note that if the exception will be thrown by the constructor, the program will not reach the insertion of the element to the list.