- Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathJavaExceptionHandling.java
More file actions
Latest commit
37 lines (31 loc) · 1.12 KB
/
Copy pathJavaExceptionHandling.java
File metadata and controls
37 lines (31 loc) · 1.12 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
// https://www.hackerrank.com/challenges/java-exception-handling/problem
importjava.util.Scanner;
publicclassJavaExceptionHandling {
publicstaticfinalMyCalculatorMY_CALCULATOR = newMyCalculator();
publicstaticfinalScannerSCANNER = newScanner(System.in);
publicstaticvoidmain(String[] args) {
while (SCANNER.hasNextInt()) {
intn = SCANNER.nextInt();
intp = SCANNER.nextInt();
try {
System.out.println(MY_CALCULATOR.power(n, p));
} catch (Exceptione) {
System.out.println(e);
}
}
}
privatestaticclassMyCalculator {
publiclongpower(intbase, intpower) throwsException {
if (base == 0 && power == 0) {
thrownewException("n and p should not be zero.");
} elseif (base < 0 || power < 0) {
thrownewException("n and p should not be negative.");
}
longresult = 1;
for (inti = 0 ; i < power ; i++) {
result *= base;
}
returnresult;
}
}
}