본문 바로가기
코딩 공부방 👩‍💻👨‍💻/알고리즘

[Java] 해커랭크(HackerRank) : Java Static Initializer Block

by ByJinnie 2023. 2. 7.
반응형

[문제] 

Static Initializer Block(정적 초기화 블록)을 연습하는 문제입니다. 밑변과 높이가 입력되면, 평행 사변형의 넓이를 출력해야 합니다. 밑변과 높이는 모두 0보다 큰 정수여야 하며, 이 조건을 충족하지 않을 경우 에러 메시지가 출력돼야 합니다.

 

이 문제에서는 반드시 Static Initializer Block(정적 초기화 블록)을 활용해서 값 입력(Scanner)과 flag 조건 판별(if-else문)을 해야 합니다.

정적 초기화 블록은 'static {}'로 작성할 수 있으며, 이는 클래스가 로딩될 때 1번만 호출됩니다.(생성자보다 우선 실행됨)

 

 

예시)

입력값 :

1

3

 

출력값:

3

 

입력값 :

-1

2

 

출력값:

java.lang.Exception: Breadth and height must be positive

 

 

 

[코드]

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

public class Solution {
    // Write Code here
    
    // Declare static variables
    static boolean flag = true; 
    static int B, H;

    // Static Initializer Block
    static{
    // Input
        Scanner scan = new Scanner(System.in);
        B = scan.nextInt();
        H = scan.nextInt();
        scan.close();
        
        // Return flag value(true or false)
        if(B>0 && H>0){
            flag = true;

        }else if(B<=0 || H<=0){
            flag = false;
            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

 

* 문제 출처 (Prepare > Java > Introduction > Java Static Initializer Block)

: https://www.hackerrank.com/

 

HackerRank

HackerRank is the market-leading technical assessment and remote interview solution for hiring developers. Learn how to hire technical talent from anywhere!

www.hackerrank.com

 

반응형

댓글