Java Day 17- More Exceptions




Write a Calculator class with a single method: int power(int,int). The power method takes two integers, n and p, as parameters and returns the integer result of n^p. If either n or p is negative, then the method must throw an exception with the message: n and p should be non-negative



  1. import java.util.*;
  2. import java.io.*;
  3. //Write your code here
  4. class Calculator {
  5. public int power(int n, int p) throws Exception {
  6. if (n < 0 || p < 0)
  7. throw new Exception("n and p should be non-negative");
  8. return (int) Math.pow(n, p);
  9. }
  10. }
  11. class Solution{
  12. public static void main(String[] args) {
  13. Scanner in = new Scanner(System.in);
  14. int t = in.nextInt();
  15. while (t-- > 0) {
  16. int n = in.nextInt();
  17. int p = in.nextInt();
  18. Calculator myCalculator = new Calculator();
  19. try {
  20. int ans = myCalculator.power(n, p);
  21. System.out.println(ans);
  22. }
  23. catch (Exception e) {
  24. System.out.println(e.getMessage());
  25. }
  26. }
  27. in.close();
  28. }
  29. }
download android app

Popular HackerRank Java Solutions








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