【问题标题】:I have a problem in java method code which returns the division of two numbers我在返回两个数字的除法的java方法代码中有一个问题
【发布时间】:2020-02-19 19:33:25
【问题描述】:

在此代码中实现了除法方法,因此我想处理 3 种使用 try catch 和 throws 未定义除法的情况,但它给了我一条错误消息,即除法方法必须返回 float 。 包计算器3;

//类实现接口 公共类实现实现 calc {

//Add function
    public int add(int x, int y) {
        int ans1 = x + y ; 
        return ans1 ;

    }

    //Divide function
    public float divide(int x, int y) throws RuntimeException{
        try {
            if(y == Double.POSITIVE_INFINITY || y == Double.NEGATIVE_INFINITY || y == 0 ) {
                throw new ArithmeticException("invalid_division");

            }
            else {        
                return x / y ;
            }

        }catch  (ArithmeticException invalid_division ) {
            System.out.println("invalid_division");
        }
}
}   

【问题讨论】:

  • float 应该已经处理了这些排列。您所要做的就是捕获产生的异常或让它们冒泡给调用者。
  • x 和 y 是整数,所以 x/y 执行整数除法,而不是浮点除法。您需要将其中一个转换为浮点数才能获得正确答案。此外,您可能应该使用双精度数,而不是浮点数,以获得更准确的结果。
  • 并且,如果进行浮动(float 或double)除法,请注意几乎不会抛出任何异常(结果可能是NaN 或一些infinity)规范: 15.17.2. Division Operator /

标签: java methods try-catch throw


【解决方案1】:

您的divide 返回类型是float。

int 永远不会等于 Double.POSITIVE_INFINITY 或 Double.NEGATIVE_INFINITY,因为它们不在它们的可能值范围内。

如果被捕获,该函数不会抛出错误。

获得3分以上:

//divide
public float divide(int x, int y) throws ArithmeticException{
        if (y == 0) throw new ArithmeticException("invalid_division");
        return (float)x / y; // cast x to float so a float will result
}

【讨论】:

  • 所以我应该只为 y = 0 例外
【解决方案2】:

一旦捕获异常,您实际上并没有抛出异常,因此编译器会抱怨您在 divide() 方法中缺少返回。

添加:

throw e;

到你的 catch 子句

【讨论】:

    猜你喜欢
    • 2011-09-14
    • 1970-01-01
    • 2012-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-04
    • 2015-05-01
    相关资源
    最近更新 更多