Input Format

Each line of the input contains two integers,  and . The locked stub code in the editor reads the input and sends the values to the method as parameters.

Constraints

Output Format

Each line of the output contains the result , if both  and  are positive. If either  or  is negative, the output contains "n and p should be non-negative". If both  and  are zero, the output contains "n and p should not be zero.". This is printed by the locked stub code in the editor.


hackerrank java exception handling solution


Java Exception handling problem solution | HackerRank

import static java.lang.Math.pow;

class MyCalculator {
    /*
    * Create the method long power(int, int) here.
    */
    public long power(final int n, final int p) throws Exception {
        if (n < 0 || p < 0) {
            throw new Exception("n or p should not be negative.");
        } else if (n == 0 && p == 0) {
            throw new Exception("n and p should not be zero.");
        }
        return (long)pow(n, p);
   }
}

Full program


import java.util.Scanner;
class MyCalculator {

public static int power(int n, int p) throws Exception{
    if(n < 0 || p < 0){
        throw new Exception ("n or p should not be negative.");
    }else if(n==0 && p ==0){
        throw new Exception("n and p should not be zero.");
    }

     else {
        return ((int)Math.pow(n,p));
    }
}
}

public class Solution {
    public static final MyCalculator my_calculator = new MyCalculator();
    public static final Scanner in = new Scanner(System.in);
    
    public static void main(String[] args) {
        while (in .hasNextInt()) {
            int n = in .nextInt();
            int p = in .nextInt();
            
            try {
                System.out.println(my_calculator.power(n, p));
            } catch (Exception e) {
                System.out.println(e);
            }
        }
    }
}