2014-11-08 60 views
0

我得到了一个问题,我正在写一个Java类,它的承包商将需要两个参数,参数是一个图像对象 - BufferedImage,我需要检查图像的宽度和高度。如何拒绝Java构造函数中的不合格参数?

一个规则是 - imageOne的怀特需要是相同imageTwo,如果不是我 想要的应用程序停止,并提高信息告诉用户该 两个图像都不好(不合格)。

我想应该有一个常规的方式来处理我的想法在Java中,也许我需要rasie异常?

对不起,添加的代码部分,我写道:

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!!"); 
    } 

} 

// ... }

有人能帮忙吗?提前致谢!

里德

+0

好的,对于这项任务,到目前为止你做了什么? – SMA 2014-11-08 10:36:32

+1

一些代码我的主... – nobalG 2014-11-08 10:37:46

+0

为什么要使用'JOptionPane'给出一个错误消息。看看这个链接:http://docs.oracle.com/javase/tutorial/uiswing/components/dialog.html – 2014-11-08 10:38:37

回答

2

正确!一个例外将是这里最好的选择。

取而代之的是打印错误消息的行只需执行此操作。

throw new IllegalArgumentException("Both pictures need to be of same width"); 
0

是啊,一个异常的作品,尤其是对于一个构造函数。好电话=)

另一种选择,请查看factory method pattern