[英]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 variable
和static 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.