2013-03-13 49 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[]

相关问题