java - 我在返回两个数字的除法的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");
}
}
}
解决方案
您的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
}
推荐阅读
- javascript - X 次访问后隐藏 div(cookie)
- sql - Vertica/SQL、Case ELSE、类型 numeric 和 boolean 不一致
- python - 用于逻辑回归的 scipy.optimize.minimize 的形状不匹配错误
- validation - 带有其他下拉列表条件的下拉列表
- git - 自动将 Git 历史从 Commit ID 变基并压缩到 HEAD 从 Branch 到 Master
- python - AttributeError 'pygame.Surface' 对象没有属性 'rect'
- android - 无法从项目生成 aar 文件
- sorting - VB6列表框在不同操作系统中排序不同
- javascript - 我将如何重组我的 React 应用程序,以便我可以将状态传递给不同路由上的组件
- c# - 在关联数组上使用 JArray.Parse(json)