这是我为 Electronics 设计的一个构造函数,用于检查 State 输入是否有效。
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");
}
}
但是在我的 main()
中,我有这样的东西:
public List<Item> shoppingCart = new ArrayList<Item>();
temp= new Electronics(name,price,quantity,weight, fragile, state);
...
shoppingCart.add(temp);
因此,即使状态缩写无效(它只是打印出状态无效),但该对象仍然会添加到 ArrayList 中。如果州缩写不正确,我该如何停止添加?
最佳答案
你应该throw an Exception并在您的 main()
中处理它,IllegakArgumentException可能是这里最合适的。
类似于:
...
else
{
throw new IllegalArgumentException("...");
}
...
在主要部分:
public List<Item> shoppingCart = new ArrayList<Item>();
try {
temp= new Electronics(name,price,quantity,weight, fragile, state);
...
shoppingCart.add(temp);
} catch (IllegalArgumentException e) {
//handle exception
}
请注意,如果构造函数抛出异常,程序将无法到达将元素插入列表的位置。
关于java - 使用类处理错误输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13782988/