有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

在Java中检查项目时出错

我在下面代码中的目标是检查输入长度是否超过小数点后两位,然后抛出异常。不过,我似乎不能把它弄对。我试图使用indexOf来获取小数点,然后我想检查它后面部分的长度。如果它大于2,我希望它抛出异常。有没有人能为这种情况提供一些建议

 public ChangeJar(final String amount) {
    int i = amount.indexOf('.');
    String temp = amount.substring(i + 2);

    if(temp.length() > 2 ){
    throw new IllegalArgumentException("Too many decimal places!");
    }

    if (amount == null || Double.parseDouble(amount) < 0) {
        throw new IllegalArgumentException("amount cannot be null!");
    }
    double amt;
    try {
        amt = Double.parseDouble(amount);
    } catch (NumberFormatException ex) {
        throw new IllegalArgumentException("Invalid entry. Format is 0.00.");
    }
    amountHelper(amt);
}

我还想知道如何在这个构造函数中添加错误检查,因为我不需要空输入。我在尝试添加错误检查时遇到一个错误,即构造函数调用必须是方法中的第一条语句。我的构造函数代码是:

public ChangeJar(final ChangeJar other){
    if(other == null){
        throw new IllegalArgumentException("Values cannot be null!");
    }
    this(other.quarters, other.dimes, other.nickels, other.pennies);
}



All suggestions are appreciated!

共 (1) 个答案

  1. # 1 楼答案

    因为Java不允许在构造函数中的super或构造函数调用之前放置任何语句。因此,您不能这样做:

    public ChangeJar(final ChangeJar other){
        if(other == null){
            throw new IllegalArgumentException("Values cannot be null!");
        }
        this(other.quarters, other.dimes, other.nickels, other.pennies);
    }
    

    您可以在正在调用的构造函数中添加检查