gpt4 book ai didi

java - 如何拒绝Java构造函数中的不合格参数?

转载 作者:行者123 更新时间:2023-12-02 05:17:20 25 4
gpt4 key购买 nike

我遇到一个问题,我正在编写一个Java类,它的承包商需要两个参数,参数是一个图像对象-BufferedImage,我需要检查图像的宽度和高度。

One rule is - imageOne's wight need be the same as imageTwo, if not I want the application to stop and raise message to tell user that the two images are not good(unqualified).

我想应该有一种常规方法可以用 Java 处理我的想法,也许我需要 rasie 异常(exception)?

抱歉,添加我编写的部分代码:

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

}

//... }

有人可以帮忙吗?提前致谢!

芦苇

最佳答案

正确!异常(exception)是最好的选择。

相反,打印错误消息的行只需执行此操作即可。

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

关于java - 如何拒绝Java构造函数中的不合格参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26816164/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com