gpt4 book ai didi

java - 构造函数应抛出 IllegalArgumentException(需要在 this() 之前检查)

转载 作者:行者123 更新时间:2023-12-02 00:59:20 26 4
gpt4 key购买 nike

我希望我的构造函数抛出 IllegalArgumentException当使用错误的参数调用时,会显示一条自写的错误消息。

public Card(int top, int left, int right) {
this(TOP.get(top) + 3 * LEFT.get(left) + 9 * RIGHT.get(right));
}

错误的参数意味着 TOP.get(top) (分别为左、右)为空,因为 Map<Integer, Integer>不包含这样的元素。问题是我无法首先测试 this()之前不允许使用代码。

最佳答案

添加一个帮助程序方法来检查输入:

public Card(int top, int left, int right) {
this(helper(top, left, right));
}

private static int helper(int top, int left, int right) {
if (TOP.get(top) == null || LEFT.get(left) == null || RIGHT.get(right) == null)) {
throw new IllegalArgumentException();
}
return TOP.get(top) + 3 * LEFT.get(left) + 9 * RIGHT.get(right);
}

关于java - 构造函数应抛出 IllegalArgumentException(需要在 this() 之前检查),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60914678/

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