Java Static Initializer Block : Hacker Rank Solution : Digit Wood

Java
,

Static initialization blocks are executed when the class is loaded, and you can initialize static variables in those blocks.

It’s time to test your knowledge of Static initialization blocks. You can read about it here.

You are given a class Solution with a main method. Complete the given code so that it outputs the area of a parallelogram with breadth B and height H. You should read the variables from the standard input.

If B<=0 or H<=0 , the output should be “java.lang.Exception: Breadth and height must be positive” without quotes.

Output Format

If both values are greater than zero, then the main method must output the area of the parallelogram. Otherwise, print “java.lang.Exception: Breadth and height must be positive” without quotes.

Sample input 1

Sample output 1

Sample input 2

Sample output 2

SOLUTION:

import java.io.*;
import java.util.*;

class MyClass {
    static int B;
    static int H;
    static {
        Scanner sc = new Scanner(System.in);
        B = sc.nextInt();
        H = sc.nextInt();
        try {
            if (B > 0 && H > 0) {
                System.out.println(B * H);
            } else {
                throw new Exception();
            }
        } catch (Exception e) {
            System.out.println("java.lang.Exception: Breadth and height must be positive");
        }
    }
}

public class Solution {

    public static void main(String[] args) {
        MyClass c = new MyClass();

    }
}

FOLLOW FOR MORE QUESTIONS AND SOLUTIONS | DIGIT WOOD

Leave a Reply

Your email address will not be published. Required fields are marked *