HackerRank Java Static Initializer Block problem solution

In this HackerRank Java Static Initializer Block problem solution, you are given a class Solution with the main method. Complete the given code so that it outputs the area of a parallelogram with breadth and height. You should read the variables from the standard input.

HackerRank Java Static Initializer Block problem solution

HackerRank Java Static Initializer Block problem solution

static int B, H;
static boolean flag = true;
static {

Scanner sc = new Scanner(System.in);
B = sc.nextInt();
H = sc.nextInt();
sc.close();
try {
if (B <= 0 || H <= 0)
throw new Exception("Breadth and height must be positive");
} catch (Exception e) {
System.out.println(e);
System.exit(0);
}

}


Post a Comment

2 Comments

  1. This comment has been removed by the author.

    ReplyDelete
  2. Referring to the video... I put my code in a static method that actually throws an Exception, then called it from a try catch block in the static initializer. That way you're not actually mimicking an exception, you're really throwing it.

    ReplyDelete