HackerRank Java- Exception Handling




Complete the function power in class MyCalculator and return the appropriate result after the power operation or an appropriate exception as detailed above.



  1. import java.util.Scanner;
  2. class MyCalculator {
  3. long power(int n, int p) throws Exception {
  4. if (n < 0 || p < 0) {
  5. throw new Exception("n or p should not be negative.");
  6. } else if (n == 0 && p == 0) {
  7. throw new Exception("n and p should not be zero.");
  8. }
  9. return (long) Math.pow(n, p);
  10. }
  11. }
  12. public class Solution {
  13. public static final MyCalculator my_calculator = new MyCalculator();
  14. public static final Scanner in = new Scanner(System.in);
  15. public static void main(String[] args) {
  16. while (in .hasNextInt()) {
  17. int n = in .nextInt();
  18. int p = in .nextInt();
  19. try {
  20. System.out.println(my_calculator.power(n, p));
  21. } catch (Exception e) {
  22. System.out.println(e);
  23. }
  24. }
  25. }
  26. }
Please click on the like button if it worked

Solution not working or have any suggestions? Please send an email to [email protected]


donate a cup of tea :)


Join Our Facebook Group

Share this solution






codesadda.com

Codesadda.com is your home of programming solutions, tutorials, video tutorials and much more. Sign Up for our weekly newsletter to get update about new content.

Like us on Facebook | Connect with us on LinkedIn | Subscribe our Channel on Youtube