題目描述

建立一個包含一個power(int,int)方法的myCalculator類別。這個power方法可以傳入n、p兩個整數作為參數,並計算np。若n或是p為負數,這個方法將會輸出一個例外,訊息為「n and p should be non-negative」。



原題網址

範例輸入

3 5
2 4
-1 -2
-1 3

範例輸出

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

解題概念

因為方法內要拋出一個Exception例外物件,因此必須在定義方法的地方使用throws關鍵字來宣告這個方法會拋出的例外類型。乘冪運算就是將底數相乘指數次,可以使用for迴圈輕易完成。

參考答案

import java.util.Scanner;

class myCalculator {

    public int power(final int n, final int p) throws Exception {
        if (n < 0 || p < 0) {
            throw new Exception("n and p should be non-negative");
        }
        int m = 1;
        for (int i = 0; i < p; ++i) {
            m *= n;
        }
        return m;
    }
}

public class Solution {

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

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