首页 > 编程语言 > 详细

java 实例 设计一个方法,计算一个数的n次幂

时间:2017-03-22 23:21:45      阅读:166      评论:0      收藏:0      [点我收藏+]

例如,首先输入  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);
   }
  }
 }
}

 

java 实例 设计一个方法,计算一个数的n次幂

原文:http://www.cnblogs.com/Angella/p/6602175.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!