繁体   English   中英

Java中的静态变量未初始化

[英]Static variable in Java not initializing

所以我在下面的代码有麻烦。

public class bw {
    public static int checked[][];
    public static BufferedImage input;

    public static void floodfill(int j, int i, int color, int spotColor, int th) throws Exception {
       input.setRGB(j, i, color);
    }

    public static void main(String args[]) throws Exception {
        BufferedImage input = ImageIO.read(new File("C:\\Users\\Aditya\\Desktop\\Lena.png"));       
        checked = new int[input.getHeight()][input.getWidth()];
        floodfill(250, 310, 0, input.getRGB(250,310), 35);
    }
}

从代码中删除了大部分不相关的部分。 静态的检查变量工作正常。 但是我在main函数中初始化的输入变量仍然为null。 它给了我来自Floodfill的空指针异常。

在main方法内部,您具有与local variablestatic attribute同名的local variable 因此,不会初始化您的静态属性,而不是初始化local variable

尝试这个

public class bw{
    public static int checked[][];
    public static BufferedImage input;

    public static void floodfill(int j, int i, int color, int spotColor, int th) throws Exception{
        input.setRGB(j, i, color);

    }
    public static void main(String args[]) throws Exception{
        input = ImageIO.read(new File("C:\\Users\\Aditya\\Desktop\\Lena.png"));       
        checked = new int[input.getHeight()][input.getWidth()];
        floodfill(250, 310, 0, input.getRGB(250,310), 35);

    }
}

您已经声明了两次变量input ,因此main方法内部的输入变量被初始化,而其他变量(静态属性)未初始化

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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