[HackerRank]-Java Static Initializer Block

네번 째 해커랭크 문제 기초이다.

Sample input 1

1
3


Sample output 1

3


예시 설명

두 수를 양수로 입력받는다. 둘중하나라도 양수면 예외 문구 출력한다.


import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

//Write your code here 여기에 작성
static int B;
static int H;
static boolean flag;

static{
    Scanner input = new Scanner(System.in);
    B = input.nextInt();
    H = input.nextInt();

    if(B > 0 && H > 0) flag = true;
    else System.out.println("java.lang.Exception: Breadth and height must be positive");
}
//여기까지
public static void main(String[] args){
		if(flag){
			int area=B*H;
			System.out.print(area);
		}
	}//end of main
}//end of class

설명

처음에 어떻게 작성할지 몰랐다. 다른코드를 건들일 수가 없었다.

요약

초기화 블럭이 있다는걸 알아두자. 초기화 블럭은 클래스가 생성될 때 무조건 수행되는 블록이라 한다.