HackerRank之Java Initializer Block

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.

Input Format

There are two lines of input. The first line contains B: the breadth of the parallelogram. The next line contains H: the height of the parallelogram.

Answer

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

public class Solution {
    public static boolean flag=true;
    public static int B=0;
    public static int H=0;

static{
    Scanner scan=new Scanner(System.in);
    B=scan.nextInt();
    H=scan.nextInt();
    scan.close();
    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

 

posted @ 2018-12-25 09:45  TroubleBoy丶  阅读(52)  评论(0编辑  收藏  举报