2013-03-13 67 views
-2
import java.io.*; 
import java.util.*; 

public class DAOImpl implements DAO 
{ 
    String xs[]; 
    public String[] readRecord() 
    { 
     try 
     { 
      BufferedReader br=new BufferedReader(new FileReader("insurance.db")); 
      BufferedReader br1=new BufferedReader(new InputStreamReader(System.in)); 


      List<String> al1= new ArrayList<String>(); 
      String next; 
      while((next=br.readLine())!=null) 
      { 
       al1.add(next); 
      } 
      System.out.println("Enter record number to read:"); 
     int x=Integer.parseInt(br1.readLine()); 

     String stream=(al1.get(x-1)); 

     String[] xs=stream.split(":"); 
     } 

     catch (FileNotFoundException ex) 
     { 
        ex.printStackTrace(); 
      } 
     catch (IOException ex) 
     { 
        ex.printStackTrace(); 
     } 
     return xs;   
    } 
    public static void main(String args[])throws Exception 
    { 
     DAOImpl d=new DAOImpl(); 

     String as[]=d.readRecord(); 
     //here compiler saying nullpointerexcdeption 

     for(int v=0;v<as.length;v++) 
     { 
      System.out.println(as[v]); 
     } 
    } 
} 

我認爲問題是聲明對象,然後調用readRecord()。主要的問題是我返回給方法readRecord()的數組。當我做對象並調用readRecord()時,它將返回String []中的所有數據。但它沒有在編譯器中給出nullPointerException。返回字符串數組時返回空指針異常。在主要方法返回數組不被複制到另一個數組,即字符串[]作爲

+2

你可以添加堆棧跟蹤嗎? – beny23 2013-03-13 12:41:18

+0

爲什麼不使用調試器並檢查變量的值? – Kai 2013-03-13 12:41:49

+0

你沒有正確地關閉BufferedReader – Joe2013 2013-03-13 12:45:10

回答

3
String[] xs=stream.split(":"); 

這個刪除的類型,即

xs=stream.split(":"); 

當你包括你創建與局部於try塊相同名稱的新變量的類型聲明,沒有分配到類級別的字段。這被稱爲「陰影」。

+0

感謝man..its完成 – Hitman 2013-03-13 12:43:05

+0

@Hitman:那你說的NullPointerException呢? – Kai 2013-03-13 12:43:53

+0

NPE是正確的。殺手使用了錯誤的xs變量,這個變量沒有啓動...... – 2013-03-13 12:46:28

1

您分配的String[] xs變量在try塊中被本地聲明,並且隱藏了被聲明爲類字段女巫的變量保留爲空的變量。請在split行中刪除類型聲明String[]