2014-07-06 54 views
0

所以我遇到以下代碼有問題。Java中的靜態變量未初始化

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

已經從代碼中取出了大部分不相關的部分。靜態的checked變量工作正常。但是我在主函數中初始化的輸入變量仍然爲空。它給了我氾濫填充的空指針異常。

+4

研究變量陰影。你的'main'方法的局部變量與你的'static'變量不同。 –

回答

3

你有一個局部變量具有相同的名稱,在主要方法內作爲local variable和作爲static attribute。因此,你的靜態屬性沒有得到,而不是初始化的local variable得到初始化

+0

打敗了我。範圍意味着一切,特別是在像Java這樣的OOP語言中。儘量避免在一個班級中儘可能地給兩個變量命名。 –

0

試試這個

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的兩倍,因此主要方法內部的輸入變量的初始化和其他(靜態屬性)不是