HackerRank Java- Static Initializer Block



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.



  1. import java.io.*;
  2. import java.util.*;
  3. import java.text.*;
  4. import java.math.*;
  5. import java.util.regex.*;
  6. public class Solution {
  7. private static int B;
  8. private static int H;
  9. private static boolean flag;
  10. static {
  11. Scanner scan = new Scanner(System.in);
  12. B = scan.nextInt();
  13. H = scan.nextInt();
  14. scan.close();
  15. if (B <= 0 || H <= 0) {
  16. System.out.println("java.lang.Exception: Breadth and height must be positive");
  17. flag = false;
  18. } else {
  19. flag = true;
  20. }
  21. }
  22. public static void main(String[] args){
  23. if(flag){
  24. int area=B*H;
  25. System.out.print(area);
  26. }
  27. }//end of main
  28. }//end of class

download android app