In this HackerRank Java Static Initializer Block problem in a java programming language, 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 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.
HackerRank Java Static initializer block problem solution.
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
static boolean flag = true;
static int B,H;
static{
Scanner scan = new Scanner(System.in);
B = scan.nextInt();
scan.nextLine();
H = scan.nextInt();
scan.close();
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
Second solution.
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
static Scanner sc = new Scanner(System.in);
static int B = sc.nextInt();
static int H = sc.nextInt();
static boolean flag = initializeInstanceVariable();
protected static boolean initializeInstanceVariable() {
boolean flag = false;
if(B>0&&H>0){
flag = true;
} else{
System.out.println("java.lang.Exception: Breadth and height must be positive");
flag=false;
}
// initialization code goes here
return flag;
}
public static void main(String[] args){
if(flag){
int area=B*H;
System.out.print(area);
}
}//end of main
}//end of class
I have a simple solution.
Scanner sc = new Scanner(System.in);
int B, H;
B = sc.nextInt();
sc.nextLine();
H = sc.nextInt();
sc.close();
if (B > 0 && H > 0) {
int area = B * H;
System.out.print(area);
} else if (B <= 0 || H <= 0) {
System.out.println("java.lang.Exception: Breadth and height must be positive");
}