Problem
Objective
Yesterday's challenge taught you to manage exceptional situations by using try and catch blocks. In today's challenge, you're going to practice throwing and propagating an exception. Check out the Tutorial tab for learning materials and an instructional video!
Task
Write a Calculator class with a single method: int power(int,int). The power method takes two integers, and , as parameters and returns the integer result of . If either or is negative, then the method must throw an exception with the message: n and p should be non-negative
.
Note: Do not use an access modifier (e.g.: public) in the declaration for your Calculator class.
Input Format
Input from stdin is handled for you by the locked stub code in your editor. The first line contains an integer, , the number of test cases. Each of the subsequent lines describes a test case in space-separated integers denoting and , respectively.
Constraints
- No Test Case will result in overflow for correctly written code.
Output Format
Output to stdout is handled for you by the locked stub code in your editor. There are lines of output, where each line contains the result of as calculated by your Calculator class' power method.
Sample Input
4
3 5
2 4
-1 -2
-1 3
Sample Output
243
16
n and p should be non-negative
n and p should be non-negative
Explanation
: and are positive, so power returns the result of , which is .
: and are positive, so power returns the result of =, which is .
: Both inputs ( and ) are negative, so power throws an exception and is printed.
: One of the inputs () is negative, so power throws an exception and is printed.
How I solved the problem
# 일부러 exception을 던질 수 있고 그 메세지를 적용하도록 코드를 짜는것이 핵심
# 또 제곱근을 구하려면 Math.pow를 써도될거같지만.. Math.pow의 return 타입은 double..!!!
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 | import java.util.*; import java.io.*; //Write your code here class Calculator { public int power(int n, int p) throws Exception { if (n < 0 || p < 0) { throw new Exception("n and p should be non-negative"); } int result = 1; for (int i = 0; i < p; i ++) { result *= n; } return result; } } class Solution{ public static void main(String[] args) { Scanner in = new Scanner(System.in); int t = in.nextInt(); while (t-- > 0) { int n = in.nextInt(); int p = in.nextInt(); Calculator myCalculator = new Calculator(); try { int ans = myCalculator.power(n, p); System.out.println(ans); } catch (Exception e) { System.out.println(e.getMessage()); } } in.close(); } } | cs |
[출처 : https://www.hackerrank.com ]
'1 Day 1 Algorithms' 카테고리의 다른 글
[2019.01.08] Interfaces (0) | 2019.01.08 |
---|---|
[2019.01.07] Queues and Stacks (0) | 2019.01.07 |
[2019.01.03] Exceptions - String to Integer (0) | 2019.01.03 |
[2019.01.02] Linked List (0) | 2019.01.02 |
[2018.12.28] Scope (0) | 2018.12.28 |
댓글