首页 > 解决方案 > 我在返回两个数字的除法的java方法代码中有一个问题

问题描述

在这段代码中实现了一个除法方法,所以我想处理 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");
        }
}
}   

标签: javamethodstry-catchthrow

解决方案


您的divide返回类型是float.

一个 int 永远不会等于Double.POSITIVE_INFINITYDouble.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
}


推荐阅读