我正在尝试编写一个程序来将任何数字的值等于任何幂,并且我想对小于零的指数实现异常处理,我成功地做到了这一点,并且还对值太大时的异常处理进行了处理输出即无穷大。
这是我的电源类,其中包含功能 Power :
public class power
{
// instance variables - replace the example below with your own
public static double Power(double base, int exp) throws IllegalArgumentException
{
if(exp < 0){
throw new IllegalArgumentException("Exponent cannot be less than zero");
}
else if(exp == 0){
return 1;
}
else{
return base * Power(base, exp-1);
}
}
}
这是测试类:
public class powerTest
{
public static void main(String [] args)
{
double [] base = {2.0, 3.0, 2.0, 2.0, 4.0 };
int [] exponent = {10, 9, -8, 6400, 53};
for (int i = 0; i < 5; i++) {
try {
double result = power.Power(base[i], exponent[i]);
System.out.println("result " + result);
}
catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
catch (ArithmeticException e) {
System.out.println(e.getMessage());
}
}
}
}
这是测试的输出:
result 1024.0
result 19683.0
Exponent cannot be less than zero
result Infinity
result 8.112963841460668E31
我的问题是如何通过 ArithmeticException 处理“浮点溢出”的内容来获得“结果无穷大”来表达其他内容?
提前致谢。
最佳答案
当你捕获异常时,在这里
catch (ArithmeticException e) {
System.out.println(e.getMessage());
}
就这么做
System.out.println("Floating point Overflow")
也(如果您想添加更多)或用此语句替换第一个打印
就像你说的那样,“你会得到无穷大的结果”,通过 ArithmeticException 处理来表达其他内容”
关于Java 无穷大异常处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27348657/