例如,首先输入  2 4就是计算2的4次方,如果出现负数,则抛出异常

代码如下:

import java.util.*;
import java.util.Scanner;
class MyCalculator {
    long power(int n, int p) throws Exception {
        if (n < 0 || p < 0) {
            throw new Exception("n and p should be non-negative");
        } else {
            return (long) Math.pow(n, p);
        }
    }
}
class Solution {

 public static void main(String[] args) {
  Scanner in = new Scanner(System.in);

  while ( in .hasNextInt()) {
   int n = in .nextInt();
   int p = in .nextInt();
   MyCalculator my_calculator = new MyCalculator();
   try {
    System.out.println(my_calculator.power(n, p));
   } catch (Exception e) {
    System.out.println(e);
   }
  }
 }
}

 

相关文章:

  • 2021-07-15
  • 2021-08-06
  • 2021-10-03
  • 2022-12-23
  • 2021-11-26
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-01-05
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-12-04
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案