forked from SedaKunda/hackerrank
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExceptionHandling.java
More file actions
57 lines (50 loc) · 1.27 KB
/
ExceptionHandling.java
File metadata and controls
57 lines (50 loc) · 1.27 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
55
56
57
/*
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".
*/
import java.util.*;
import java.util.Scanner;
class myCalculator {
public String power (int n, int p) throws NegativeException {
int power = 0;
try {
if (n<0|p<0) {
throw new NegativeException();
}
else {
power = (int) Math.pow(n, p);
return power +"";
}
}
catch (NegativeException e) {
return "java.lang.Exception: n and p should be non-negative";
}
}
}
class NegativeException extends Exception
{
private static final long serialVersionUID = 1L;
public NegativeException()
{
super();
}
}
class ExceptionHandling{
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);
}
}
}
}