简体   繁体   中英

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

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?

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.

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);
        }
    }
}

You should declare static variables outside the static code block.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM