-1

I have a little difficulty understanding how the static block works

import java.io.*;
import java.util.*;

public class Solution {

    static {

            Scanner sc = new Scanner(System.in);
            int B =  sc.nextInt();
            int H =  sc.nextInt();
            boolean flag= false;
            if(B<=0 || H<=0){
                  flag= false;
                  System.out.println("java.lang.Exception: Breath and Hieght must be positive");
                  }
             }

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

        }

    }

when I try to run it says cannot find symbol flag, B, H. Can anyone explain why?

  • 5
    Variables declared in the static block are local to that block and cannot be seen outside of it. They would need to be declared against the class. – mwarren Apr 30 '20 at 07:46
  • 2
    They're local variables. You can't use local variables outside the scope in which they are declared. – khelwood Apr 30 '20 at 07:47

3 Answers3

0

The scope of the variable is within static block or any block for that matter. You should declare it outside the block and define it inside ur static block.

Wall
  • 88
  • 1
  • 9
0

All the variables in your static block will be detroyed at the end of the execution of the block. To prevent this, you could declare those variables as fields like this

import java.io.*;
import java.util.*;

public class Solution {

    private static int B;
    private static int H;
    private static boolean flag;

    static {
        Scanner sc = new Scanner(System.in);
        B =  sc.nextInt();
        H =  sc.nextInt();
        flag = false;
        if(B<=0 || H<=0){
            flag= false;
            System.out.println("java.lang.Exception: Breath and Hieght must be positive");
        }
    }

    public static void main(String[] args){
        if(flag){
            int area=B*H;
            System.out.print(area);
        }
    }
}
Mathiewz
  • 189
  • 1
  • 12
  • By default, you should always use the lowest visibility needed to avoid to expose unwanted fields to other classes – Mathiewz Apr 30 '20 at 08:07
0

You should declare static variables outside the static code block.

Sacher
  • 11
  • 2