DEV Community

Beatriz Maciel
Beatriz Maciel

Posted on • Edited on

HackerRank #9 | Static Initializer Block | 🇧🇷

Este problema pede para que seja calculada a área de um paralelograma com largura B e altura H. Caso B <= 0 e H <=0, o console deve retornar a mensagem "java.lang.Expection: Breadth and height must be positive".

Static

Além disso, é importante que seja usado um bloco Static de inicialização. A vantagem do private static methods é a reutilização se for necessário reinicializar a classe variável.

A sintaxe de uma inicialização static é:


public class staticTest {

    static String s;
    static int n;
    static double b;

    static {
        s = "Eu sou estático";
        n = 500;
        d = 4000.0001;
    }
}

Enter fullscreen mode Exit fullscreen mode

O código oferecido no problema é o seguinte:



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

public class Solution {


        //... espaço para escrever o código


public static void main(String[] args){
        if(flag){
            int area=B*H;
            System.out.print(area);
        }

    }//end of main

}//end of class


Enter fullscreen mode Exit fullscreen mode

Try / Catch

Para resolver o problema, é importante usar tanto o bloco static quanto o try / catch. Toda vez que temos uma CheckedException, podemos usar o try / catch para desviar os erros, mantendo o funcionamento dos comandos.

A sintaxe do Try / Catch é:


try {

} catch (Exception ex) {

}

Enter fullscreen mode Exit fullscreen mode

Às vezes precisamos usar um throw new Exception("mensagem"), para especificar qual exceção queremos passar e facilitar a correção de bugs futuros.

Dessa forma, a resolução do problema se dá nos seguintes passos:

  • Dentro da classe Solution, passar variáveis que sejam static.
  • Criar um Scanner para fazer input dos números.
  • Validar, através de um boolean, o flag que já estava especificado na main do problema.
  • Passar as variáveis B e H para calcular a o paralelograma.
  • Abrir o bloco static{}
  • Introduzir o bloco try / catch, especificando que se (if) a flag seja false, é necessário aplicar o throw new Exception() e imprimir a exceção que foi pedida.

Sendo assim, a solução final, dentro da classe Solution, fica:


        static Scanner sc = new Scanner(System.in);
        static boolean flag = true;
        static int B = sc.nextInt();
        static int H = sc.nextInt();

static {

        try{
            if(B <= 0 || H <= 0){
                flag = false;
                throw new Exception("Breadth and height must be positive");
            }
            } catch (java.lang.Exception ex){
            System.out.println(ex);
        }

Enter fullscreen mode Exit fullscreen mode

==========

Referências

Static

Documentação oficial:

Exemplo de sintaxe:

Try / Catch

Exceções e sintaxe

============

Essa publicação faz parte de uma série de exercícios resolvidos em Java no HackerRank. Acesse a série completa:

Top comments (0)

Great read:

Is it Time to go Back to the Monolith?

History repeats itself. Everything old is new again and I’ve been around long enough to see ideas discarded, rediscovered and return triumphantly to overtake the fad. In recent years SQL has made a tremendous comeback from the dead. We love relational databases all over again. I think the Monolith will have its space odyssey moment again. Microservices and serverless are trends pushed by the cloud vendors, designed to sell us more cloud computing resources.

Microservices make very little sense financially for most use cases. Yes, they can ramp down. But when they scale up, they pay the costs in dividends. The increased observability costs alone line the pockets of the “big cloud” vendors.