Java.Lang.Exception with Math.pow



我正在创建一个方法,该方法将两个整数 base 和 power 作为参数并找到 base^power。如果基数或幂为负数,则该方法必须抛出一个异常,指出"n 和 p 应该是非负数"。

这是我的代码:

import java.lang.*;
class MyCalculator{
    public int power(int base, int power){
       if (base < 0 && power < 0){
            System.out.println("java.lang.Exception: n and p should be non-negative");
       }
            int calculator = (int) Math.pow(base, power);
            return calculator; 
    }
}

这是我的意见:

3 5
2 4
-1 -2
-1 3

这是我的输出:

243
16
java.lang.Exception: n and p should be non-negative
1
-1

这是我的目标输出:

243
16
java.lang.Exception: n and p should be non-negative
java.lang.Exception: n and p should be non-negative

有人可以告诉我如何解决这个问题以及为什么最后出现"1"和"-1"吗?

base < 0 && power < 0

应该是:

base < 0 || power < 0

此外,您并没有真正抛出异常,您只是打印到控制台。

你应该像这样抛出异常(如果你想抛出一个(:

import java.lang.*;
class MyCalculator{
    public int power(int base, int power){
       if (base < 0 || power < 0){
            throw new Exception("n and p should be non-negative");
       }
            int calculator = (int) Math.pow(base, power);
            return calculator; 
    }
}

您可能想阅读:https://docs.oracle.com/javase/tutorial/essential/exceptions/

首先,如果可以观察调用此方法的代码,我们可以给出一个更近的原因。

其次,问题可能是您使用"&&"比较器来确定两个参数都应该为负数才能打印"异常">

,同时我认为您想使用"||"比较器,这意味着只有一个参数需要为负数才能进入"异常">

最新更新