代码之家  ›  专栏  ›  技术社区  ›  Offa

将字符串添加到TreeSet时出现NullPointerException<String>〔重复〕

  •  2
  • Offa  · 技术社区  · 12 年前

    我的问题是我在这个代码中找不到错误。我想用从文件中读取的字符串填充构造函数中程序的一个字段(字符串集)。

    `

    public AnagramUserInput(){
        Set<String> result = new TreeSet<String>();
        Set<String> lexic = new TreeSet<String>();
        File lexicon = new File("C:/Users/Konstanty Orzeszko/Desktop/do testu/english_words_WIN.txt");
        try{
            BufferedReader br = new BufferedReader(new FileReader(lexicon));
            String word;
    
            while(((word = br.readLine()) != null)) {
                this.lexic.add(word);//Exception is throwned right in this line
             }
            br.close();
        }catch(IOException exc) {
            System.out.println(exc.toString());
            System.exit(1);
        }
    }`
    

    你能告诉我出了什么问题/怎么修吗? 谢谢。

    4 回复  |  直到 12 年前
        1
  •  2
  •   Konstantin Yovkov    11 年前

    this.lexic 评估为 null 。请注意 this.lexis 不指向构造函数的本地 lexic 变量,但为实例的一个。

    如果你想 将String添加到构造函数的 词汇的 变量,只需去掉 this 关键字:

    lexic.add(word);
    
        2
  •  1
  •   Rahul    12 年前

    我看到的唯一问题是

    this.lexic.add(word); // this.lexic
    

    移除 this 。因为构造函数实例化了类。即使在创建对象之前,您也在尝试使用 ,这是错误的。

        3
  •  1
  •   Reimeus    12 年前

    很可能您有另一个名为 lexic 作为类实例变量。(如果不是这样的话,上面的代码将不会编译)

    因此,你很可能在跟踪 result 变量代替

    Set<String> lexic = new TreeSet<String>();
    

    具有

    lexic = new TreeSet<String>();
    
        4
  •  0
  •   codingenious    12 年前
    this.lexic.add(word);
    

    你在构造函数中使用这个,也就是说,你在创建对象的过程中使用它。这就是你获得NPE的原因。去掉这个,它就会起作用。

    如果你也把填充部分放在一个方法中,那就意味着

    Set<String> lexic = new TreeSet<String>();
    

    也是在相同的方法中,那么“this”也不会起作用,因为“this”不适用于局部级别的变量。但在这种情况下,它也不会给出NPE,而是编译器错误。

    此代码工作正常,您可以检查一次:

    public AnagramUserInput()
    {
        Set<String> result = new TreeSet<String>();
        Set<String> lexic = new TreeSet<String>();
        File lexicon = new File("output.txt");
        BufferedReader br = null;
        try{
            br = new BufferedReader(new FileReader(lexicon));
            String word;
    
            while(((word = br.readLine()) != null)) {
                lexic.add(word);//Exception is throwned right in this line
             }
    
        }catch(IOException exc) {
            System.out.println(exc.toString());
            System.exit(1);
        }
    
        finally
        {
           if (br != null)
           {
                try
                {
                    br.close();
                }
                catch (IOException e)
                {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
                }
           }
        }
    
        System.out.println(lexic);
    }
    

    只需确保文件位于所需的正确位置即可。