Why does a variable declared in static block when used in main method is not not found?

455 Views Asked by At

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?

3

There are 3 best solutions below

0
Wall On

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.

1
Mathiewz On

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);
        }
    }
}
0
Sacher On

You should declare static variables outside the static code block.