forked from builder-of-web3/HackR_Java_Code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathException Handling2
More file actions
54 lines (42 loc) · 1.33 KB
/
Exception Handling2
File metadata and controls
54 lines (42 loc) · 1.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
Create a class myCalculator which consists of a single method power(int,int). This method takes two integers, nn and pp, as parameters and finds npnp. If either nn or pp is negative, then the method must throw an exception which says "n and p should be non-negative".
Please read the partially completed code in the editor and complete it. Your code mustn't be public.
No need to worry about constraints, there won't be any overflow if your code is correct.
Sample Input
3 5
2 4
-1 -2
-1 3
Sample Output
243
16
java.lang.Exception: n and p should be non-negative
java.lang.Exception: n and p should be non-negative
import java.util.*;
import java.util.Scanner;
class myCalculator{
int power(int n, int p) throws Exception{
if(n<0 || p<0)
throw new Exception("n and p should be non-negative");
return (int)Math.pow((double)n,(double)p);
}
}
class Solution{
public static void main(String []argh)
{
Scanner in = new Scanner(System.in);
while(in.hasNextInt())
{
int n = in.nextInt();
int p = in.nextInt();
myCalculator M = new myCalculator();
try
{
System.out.println(M.power(n,p));
}
catch(Exception e)
{
System.out.println(e);
}
}
}
}