【问题标题】:Throwing IllegalArgumentException in Parameterized Constructor Java在参数化构造函数 Java 中抛出 IllegalArgumentException
【发布时间】:2018-07-17 06:54:17
【问题描述】:

这是我的代码:

public StyleRay(Point endpoint, int direction, String style)
{
    if(endpoint == null || style == null)
        throw new IllegalArgumentException("A point or string cannot be null");
    else if(direction < 0 || direction > 359)
        throw new IllegalArgumentException("The direction needs to be between 0 and 360");
    else if(style != "dotted" || style != "dashed" || style != "double")
        throw new IllegalArgumentException("The style needs to be double, dashed, or dotted");
    else
    {
        this.endpoint = new Point(endpoint);
        this.direction = direction;
        this.style = new String(style);
    }
}

以下是我的作业要求:

一个参数化的构造函数,它将接收端点(作为一个点)和方向(作为一个 int) 和样式(作为字符串)。如果接收到的 Point 或接收到的 String 为空,则 throw new IllegalArgumentException(); 如果方向不在 0 和 359(含)之间,则 throw new IllegalArgumentException(); 此外,如果收到的样式不等于“double”或“dashed”或“dotted”,那么 throw new IllegalArgumentException(); 如果方向和样式都OK,则将数据初始化为Point、int和String 已收到。确保在这种情况下使用深层副本。

我知道我检查样式是虚线、虚线还是双线的部分有问题,因为当我将其注释掉时,除了该部分之外,一切正常。就现在的情况而言,它只会向所有内容抛出 IllegalArgumentExceptions。

我觉得这是一个非常简单的解决方法,我只是没有做正确的事情,但我是这方面的初学者,不知道接下来应该尝试什么。

我最初是这样尝试的,

else if(style.equals("dotted") == false) || etc, etc, etc)

但这也没有用。

感谢任何帮助。

【问题讨论】:

    标签: java class constructor


    【解决方案1】:

    试试这个:

    if (!style.equals("dotted") && !style.equals("dashed") && !style.equals("double"))        
        throw new IllegalArgumentException("The style needs to be double, dashed, or dotted"); 
    

    【讨论】:

    • 成功了,谢谢。所以 ”!”在前面告诉它检查它是否不等于我假设的?
    • 太棒了!是的。
    猜你喜欢
    • 2015-05-13
    • 2020-03-16
    • 1970-01-01
    • 2011-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多