[英]Static variable in Java not initializing
So I am having trouble with the following code. 所以我在下面的代码有麻烦。
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);
}
}
Have taken out most of the irrelevant part from the code. 从代码中删除了大部分不相关的部分。 The checked variable which is static is working fine. 静态的检查变量工作正常。 But the input variable which I have intialized in the main function is still null. 但是我在main函数中初始化的输入变量仍然为null。 It gived me null pointer exception from floodfill. 它给了我来自Floodfill的空指针异常。
You have a local variable with the same name, inside main method as a local variable
and as a static attribute
. 在main方法内部,您具有与local variable
和static attribute
同名的local variable
。 Therefore your static attribute is not get initialized instead of the local variable
getting initialized 因此,不会初始化您的静态属性,而不是初始化local variable
Try this 尝试这个
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);
}
}
You have declared variable input
twice, so the input variable inside main method is initialized and the other(the static attribute) is not 您已经声明了两次变量input
,因此main方法内部的输入变量被初始化,而其他变量(静态属性)未初始化
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.