-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。

4

2 回答 2

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

去掉上面的类型,即

xs=stream.split(":");

当您包含类型声明时,您正在创建一个与 try 块本地名称相同的新变量,而不是分配给类级字段。这被称为“阴影”。

于 2013-03-13T12:42:16.513 回答
1

String[] xs您分配的变量是在try块中本地声明的,并且隐藏了声明为类字段的变量,女巫仍然为空。删除该行中的类型String[]声明split

于 2013-03-13T12:45:32.983 回答