我遇到了一个问题,我正在写一个Java类,它的承包商需要两个参数,参数是一个图像对象-BufferedImage,我需要检查图像的宽度和高度。
一条规则是-imageOne的权重需要与imageTwo相同,如果不是我希望应用程序停止并引发消息,告诉用户两个图像不好(不合格)。
我想应该有一种常规的方法来处理我在Java中的想法,也许我需要一个例外?
抱歉,添加了我写的部分代码:
public class Replacer { // This class to merge two images, so it need they have same width.
private BufferedImage smallImage;
private BufferedImage bigImage;
Replacer(BufferedImage smallImage, BufferedImage bigImage) {
// I want the smallImage and bigImage have same weight
this.setSmallImage(smallImage);
this.setBigImage(bigImage);
wOfNewScreen = bigImage.getWidth();
hOfSmallImage = smallImage.getHeight();
hOfBigImage = bigImage.getHeight();
if (wOfNewScreen != samllImage.getWidth()) {
System.out.println("ERROR: The two images don't have same width!!");
}
}
//。。。}
有人能帮忙吗?提前感谢!
Reed
正确!例外情况是最好的选择。
相反,打印错误消息的行只需执行此操作。
throw new IllegalArgumentException("Both pictures need to be of same width");
是的,异常有效,尤其是对于构造函数。呼叫良好=)
另一个选项,查看工厂方法模式。